| Bandar (45) | |||||
|
Is this example correct? This example from a book Constructor of the Base Class
Constructor of the Derived Class (inherited from the base class)
Why the initialized list of the base class constructor doesn't match the initialized list of the derived class constructor? I know this book is a little bit old, I'm not sure if this wrong in VC++ 2010? | |||||
|
|
|||||
| pogrady (525) | |
| Because there is a default value for nat, which is U.S.A (which is missing a period btw), so there is no reason to include it, but it should have been done anyway. | |
|
|
|
| cire (2347) | ||
The code is incorrect anywhere. An argument must be supplied for nat since a value is supplied for s. One cannot skip arguments in the middle of a parameter list and expect default arguments to be supplied for it. Default values are only given to arguments not supplied at the end of a parameter list. If the Person constructor was changed to: Person::Person(char*n="", int s=1, char* nat="U.S.A") the derived class constructor would work. Leaving the base class the same and adjusting the derived class to supply the argument would also work. | ||
|
Last edited on
|
||
| Bandar (45) | |||||||
|
@pogrady @cire thank guys for your helping. @cire This is what I thought. I have another question. Why this example doesn't work. main file
.cpp file for the Person Class
.h file for the Person Class
It works only if I put them in main file. In other words, without separate them. The error in this line Person creator("Bjarne Stroustrup", "Denmark");Error: no instance of constructor "Person::Person" matches the argument list. Any suggestions | |||||||
|
|
|||||||
| tvrameshmc (54) | |||
In .cpp file don't write default parameters initialization. Write as below.
In .h file you have to write default parameters initialization as below. Person(char* n="", char* nat="U.S.A", int s=1); | |||
|
|
|||
| Bandar (45) | |
|
@tvrameshmc thank you so much. It worked. | |
|
|
|