Hi I just finished taking my final exam. There was a questions that said, "define the common ancestor problem in C++", and state what feature of the language is used to address this problem.
I don't remember ever learning about the common ancestor problem in class or ever hearing about it. However I wrote the following:
I said it had to do with inheritance. If a parent class and a child class define the same method with the same method signature. So for instance if I have class Parent and class Child.
In class Parent I have
void sayHello(){
cout << "hello I'm a parent" <<endl;
}
then in class Child I have
void sayHello(){
cout << "hello I'm a child" <<<endl;
}
then if I have
Parent* p1;
Child* c1 = new Child();
p1 = & c1;
If I call p1.sayHello()
I will call the method sayHello()
from the parent class even though it's bounded to an instance of Child type.
So to address this we must use the virtual keyword and say
virtual void sayHeyllo(){
.....
}
so that wen I call p1.sayHello() it calls the method from the Child class and not the parent class.
Is this correct? I just took a guess, but it kind of makes sense. I googled C++ common ancestor problem, but nothing came up. do you know if I'm right?
Thanks. T