Reputation: 20309
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
Upvotes: 2
Views: 248
Reputation: 755259
In order to do this you need to make the Parent
declaration a pointer or a reference.
Parent* obj = new Son();
In it's current form your declaring obj
to be an instance of Parent
. This means the assignment from Son()
doesn't create a reference to a Son
instance, instead it slices the object into a Parent
value.
Upvotes: 7