Implementing abstract class members in a parent class

后端 未结 4 947
小蘑菇
小蘑菇 2020-12-21 09:07

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

4条回答
  •  北海茫月
    2020-12-21 09:32

    ITalk contains the pure virtual function SayHi(), so if you want to be able to instantiate a class that derives from ITalk that class must implement SayHi().

    class Child : public Parent, public ITalk
    {
    public:
      void SayHi() { std::cout << "Hi!" << std::endl; }
    };
    

    Alternatively, Parent can inherit from ITalk (but not Child) and the code you've posted will work.

    Also, when implementing a base class with virtual functions you must define virtual destructors for those base classes. So ITalk should be:

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

    If you don't do that the following produces undefined behavior

    ITalk* lChild = new Child();
    lChild->SayHi();
    delete lChild;
    

提交回复
热议问题