In C++ inheritance, I understood that subclass's constructor cannot directly initialize the members of the parent class.
If it is so, why doesn't the code below cause an error?
class Person
{
protected:
string _name;
int _age;
};
class teacher : public Person
{
public:
teacher()
{
_name = "teacher";
}
private:
string _title;
};
Isn't the teacher
constructor here directly assigning a value to the parent class's member?
It is correct that a derived class cannot initialize base class members.
Members initialization can be done only by the base class, and it is done anyway before the derived class constructor executes.
But the statement:
_name = "teacher";
Is an assignment statement, and not initialization.
And a publicly derived class can assign protected members of its base class.
This is why your code compiles.
If you actually use initiazation instead of assignment, e.g. like this (in an initiazation list):
//---------vvvvvvvvvvvvvvvvv
teacher() : _name("teacher")
{
}
It will cause a compilation error.
MSVC for example issues:
error C2614: 'teacher': illegal member initialization: '_name' is not a base or member