Let's say that I want to make use of base class constructor in order to create derived class objects.
This is my approach on how to do it:
class base
{
int x, y, z;
public:
base(int x, int y, int z)
:
x(x),
y(y),
z(z)
{
std::cout << "base class constructor called\n";
}
int get_x() const { return x; }
int get_y() const { return y; }
int get_z() const { return z; }
};
class derived : public base
{
int value;
public:
derived(int x, int y, int z, int value)
:
base(x, y, z),
value(value)
{
std::cout << "derived class constructor called\n";
};
int get_val() const { return value; } ;
};
My question: Is this the correct way of solving that problem? Or, is there some better approach on how to use base class constructor in derived class constructor?
CodePudding user response:
Adding an appropriate base class constructor 'call' in the initialization list for your derived class constructor is perfectly acceptable and normal. (In fact, for the example that you've shown, omitting that constructor from the initialization list will cause the code to be ill-formed: the compiler will then attempt to default-construct the the base
object and, since you have specified an explicit, argument-taking constructor, the default constructor for your base
class is deleted.)
One thing to note, however, is that that base class constructor will be executed first, even if you rearrange the specification order in that initialization list.
Take the slightly modified code below:
class derived : public base {
int value;
public:
derived(int x_, int y_, int z_, int value_) // IMHO, using argument names same as members not good
:
value(value_), // Rearrange list to have this appear first ...
base(x_, y_, z_) // ...but this is STILL called before the above
{
std::cout << "derived class constructor called\n";
} // Note: Unnecessary semicolon after function (as also after getter).
int get_val() const { return value; } // ; unnecessary
};
For this code, clang-cl gives this:
warning : field 'value' will be initialized after base 'base' [-Wreorder-ctor]
And MSVC gives:
warning C5038: data member 'derived::value' will be initialized after base class 'base'