Is this a legal way of calling a base class constructor.
The Base Class is as follows
class base_class
{
public:
base_class(int x, int y);
protected:
int a;
int b;
};
base_class::base_class(int x,int y)
{
a=x;
b=y;
}
The Derived class is a follows
class derived_class: public base_class
{
public:
derived_class(int x,int y,int z);
protected:
int c;
};
derived_class:: derived_class(int x,int y,int z):base_class(x,y) /*Edited and included the scope resolution operator*/
{
c=z;
}
Is this way of defining a derived class constructor legal in C++, if yes how is the base class constructor called?
This is the correct (and only) way to initialise your base class(es) if you’re invoking a non-default constructor — if you add the second colon to the scope-resolution operator, of course.
It is more usual to initialise all of your members in the “initializer list” (the section between the colon and the function body), like so:
…where
c(z)initialises yourint cto the value ofz.