I am trying to implement some derived classes that inherit part of their behaviour from the base class. The base class is something like this:
class Number {
public:
virtual string getName() = 0;
void writeName() {
string name = this->getName();
printf("My Name is %s\n", name.c_str());
}
Number() {
this->writeName();
}
};
class One : Number {
string getName() {return string("One");}
};
class Two : Number {
string getName() {return string("Two");}
};
int main() {
One *n = new One();
}
I would expect this to output "My Name is One", but I get an exception saying 'pure virtual method called'. Am I approaching this the wrong way? Or am I missing something in the declaration of the classes and members, and so I am achieving this unexcpted result? Or is this actually the expected result, and if so, how can I achieve what I need?
You get this exception because you are calling the method from inside the constructor. According to C++ rules, all virtual member functions inside a class constructor are dispatched to implementations inside the class itself, not its subclass. The logic behind this decision is that otherwise a member function would run on an object before its initialization has been completed.
There is no workaround to this: if you need constructors of subclasses to perform different actions, the code performing these actions should be placed inside subclass constructors themselves.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments