2

I have class Foo with a constructor as given:

class Foo {
 public:
   Foo(int w, char x, int y, int z);
   ...
 };

int main()
{
   Foo abc (10, 'a');
}

Can I use that constructor like this? When constructor signature do not match?

So How do I give default value?

AJ.
  • 2,561
  • 9
  • 46
  • 81

5 Answers5

5

Not unless the parameters at the tail of the signature have defaults, for example:

class Foo {
public:
    Foo(int w, char x, int y=5, int z=0);
    ...
};

If there are defaults, then you can supply only the non-defaulted parameters, and optionally some defaulted ones, i.e. any of the following invocations would be valid:

Foo abc (10, 'a');
Foo abc (10, 'a', 3);
Foo abc (10, 'a', 42, 11);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

You cannot, unless the missing constructor arguments have default values.

For example, you can do this:

class Foo {
 public:
   Foo(int w, char x, int y = 0, int z = 1);
   ...
 };

int main()
{
   Foo abc (10, 'a'); /* y is implicitly 0 and z is 1 */
}
Jon
  • 428,835
  • 81
  • 738
  • 806
1

To provide default parameters, equal them to zero or else with some default value.

class Foo {
 public:
   Foo(int w, char x, int y = 0, int z = 0) { }
   // ...
 };

Or,

class Foo {
 public:
   Foo(int w, char x, int = 0, int = 0);
   // ...
 };

// Define your constructor here, note 'no default parameters'
Foo::Foo(int w, char x, int y, int z) { }
cpx
  • 17,009
  • 20
  • 87
  • 142
0

No - if there is no constructor which accepts two arguments with matching types, you can't.

user1071136
  • 15,636
  • 4
  • 42
  • 61
  • So how do I give default value? – AJ. Dec 20 '11 at 13:54
  • Change your _declaration_ of the ctor to `Foo(int w, char x, int y = 10, int z = 10);`. Do not change the _definition_ (the place where you write the code itself). – user1071136 Dec 20 '11 at 14:03
0

I'd suggest to overload the constructor rather than providing default values.

class Foo {
public:
    Foo(int w, char x); // y = 0, z = 1
    Foo(int w, char x, int y); // z = 1
    Foo(int w, char x, int y, int z);
};

It's a matter of style in the end: cons you need to duplicate the initializer list, because constructors cannot be chained, pros readability IMHO. Make sure to read this thread.

Community
  • 1
  • 1
chrish.
  • 715
  • 5
  • 11