Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

c++ - Implementing abstract class members in a parent class

Is it possible to implement an abstract base class with members inherited from another parent class in C++?

It works in C#, so I tried doing it in C++:

// Virtual destructors omitted for brevity

class ITalk
{
public:
    virtual void SayHi() = 0;
};

class Parent
{
public:
    void SayHi();
};

class Child : public Parent, public ITalk
{
};

void Parent::SayHi()
{
    std::printf("Hi
");
}

My compiler didn't really like it though:

ITalk* lChild = new Child(); // You idiot, Child is an abstract class!
lChild->SayHi();

I can't add public ITalk to the Parent class because "base-class 'ITalk' is already a base-class of 'Parent'." I could move public ITalk up to the Parent class, but in my particular scenario that complicates a lot of things.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No because what you really have is two base classes without any knowledge of each other.

Italk    Parent
 /        / 
  |         |
  +---------+
       |
     Child

If Parent and Italk had two variables named i, there'd be two instances of "i", ITalk::i and Parent::i. To access them you'd have to fully qualify which one you wanted.

The same is true of methods, lChild has two methods called SayHi and you need to clarify which one you mean when calling SayHi because the multiple inheritance has made it ambiguous.

You have Parent's SayHi

lChild->Parent::SayHi();

and Italk's SayHi:

lChild->ITalk::SayHi(); 

The latter is pure virtual and because its abstract needs to be overridden locally in Child. To satisfy this you'll need to define

Child::SayHi();

Which would now hide Parent::SayHi() when invoking SayHi without scoping it to the class:

lChild->SayHi() //parent's now hidden, invoke child's

Of course Child::SayHi() could call Parent::SayHi():

void Child::SayHi()
{
     Parent::SayHi();
}

which would solve your problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...