Reputation: 2569
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?
Upvotes: 2
Views: 3460
Reputation: 725
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.
Upvotes: 0
Reputation: 17577
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) { }
Upvotes: 1
Reputation: 727047
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);
Upvotes: 5
Reputation: 15725
No - if there is no constructor which accepts two arguments with matching types, you can't.
Upvotes: 0
Reputation: 437784
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 */
}
Upvotes: 2