Lets say I have a parent Class:
Class Parent{
public:
virtual void doSomething(){}
}
and two children:
Class Son: public Parent{
public:
void doSomething(){
// Do one thing
}
}
Class Daughter: public Parent{
public:
void doSomething(){
// Do another thing
}
}
If I setup an instance of a child class like this:
Parent obj = Son();
How do I properly invoke the doSomething() method that is defined by Son and not the empty function in Parent
In order to do this you need to make the
Parentdeclaration a pointer or a reference.In it’s current form your declaring
objto be an instance ofParent. This means the assignment fromSon()doesn’t create a reference to aSoninstance, instead it slices the object into aParentvalue.