nupadhyaya
nupadhyaya

Reputation: 1944

default parameters without name in c ++

Consider the functions:

void foo(int a = 3)//named default parameter
void foo1(int = 3)//unnamed default parameter

I understand the need of the first function.(The value of "a" is 3 and it can be used in the program). But the 2nd function(which is not an error) has 3 initialized to nothing. How exactly do i use this value , if i can use this value...

Upvotes: 11

Views: 5583

Answers (3)

B. Angelucci
B. Angelucci

Reputation: 51

I've found the 2nd declaration very useful when declaring an empty virtual method of a base class

virtual void doSomething(bool = false) {};

I don't want to make it pure virtual since in many derived classes I don't want to re-implement it, so I leave it empty in the base class. But I need the default value false when implementing this method in some other derived classes.

virtual void doSomething(bool en = false) {};

This is not wrong but the compiler gives the unused parameter warning

Upvotes: 1

billz
billz

Reputation: 45410

In function declaration/definition, a parameter may have or have not a name, this also applies to a parameter with default value.

But to use a parameter inside a function, a name must be provided.

Normally when declare a function with default parameter

// Unnamed default parameter. 
void foo1(int = 3);

In function definition

void foo1(int a)
{
   std::cout << a << std::endl;
}

Then you can call

foo1();   // the same as call foo1(3)
foo1(2);

Upvotes: 11

exexzian
exexzian

Reputation: 7890

In both cases 3 is assigned to an int variable that will be determined on function definition. so in later case - void foo1(int = 3); // 3 is being assigned to an int - as at declaration variable name is not required

you can relate this to - void fun(int,int); NOTE: not from default arguments point of view but from function declaration point of view

// here we have declared two int variables and its not compulsory to give its name at function declaration time.

EDIT:

As pointed out by @chethan - void foo1(int = 3){ } is valid in function definition also, but then again whats the use of doing something that you can't use later on (inside function body). for ex:

void foo1 (int a, int =2)
{
// do something
// here you wont be able to use your second argument if you haven't gave it any name
}

so I think its pointless "Not to give argument name in function definition".

Upvotes: 0

Related Questions