简体   繁体   中英

C++ Common Ancestor Problem. What is it?

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

I think they meant an inheritance diamond. When you have something like the following:

struct A {};
struct B : A {};
struct C : A {};

struct D : B, C {}; // here is the problem

The problem in D is there are two copies of A one comes from B and one from C . To solve this problem you have to use virtual inheritance :

struct A {};
struct B : virtual A {};
struct C : virtual A {};

struct D : B, C {}; // No problem!

Probably it refers to a multiple inheritance where several base classes have a common parent (" diamond inheritance "):

struct A {};
struct B1 : A {};
struct B2 : A {};
struct C : B1, B2 {};

The solution asked for should be virtual inheritance:

struct A {};
struct B1 : virtual A {};
struct B2 : virtual A {};
struct C : B1, B2 {};

This actually, normally, refers to the Diamond Problem with multiple inheritance.

Here is some detailed reference material on how C++ treats this .

I would have thought that it is referring to Diamond inheritance ( http://en.wikipedia.org/wiki/Diamond_problem )

The C++ feature that you would use to deal with this is virtual inheritance:

class Foo : virtual public Bar
{
}

Search SO for diamond inheritance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM