call to pure virtual function from base class constructor

前端 未结 8 1532
北恋
北恋 2020-11-29 03:29

I have a base class MyBase that contains a pure virtual function:

void PrintStartMessage() = 0

I want each derived class to call it in their co

8条回答
  •  广开言路
    2020-11-29 03:46

    I know this is an old question, but I came across the same question while working on my program.

    If your goal is to reduce code duplication by having the Base class handle the shared initialization code while requiring the Derived classes to specify the code unique to them in a pure virtual method, this is what I decided on.

    #include 
    
    class MyBase
    {
    public:
        virtual void UniqueCode() = 0;
        MyBase() {};
        void init(MyBase & other)
        {
          std::cout << "Shared Code before the unique code" << std::endl;
          other.UniqueCode();
          std::cout << "Shared Code after the unique code" << std::endl << std::endl;
        }
    };
    
    class FirstDerived : public MyBase
    {
    public:
        FirstDerived() : MyBase() { init(*this); };
        void  UniqueCode()
        {
          std::cout << "Code Unique to First Derived Class" << std::endl;
        }
    private:
        using MyBase::init;
    };
    
    class SecondDerived : public MyBase
    {
    public:
        SecondDerived() : MyBase() { init(*this); };
        void  UniqueCode()
        {
          std::cout << "Code Unique to Second Derived Class" << std::endl;
        }
    private:
        using MyBase::init;
    };
    
    int main()
    {
        FirstDerived first;
        SecondDerived second;
    }
    

    The output is:

     Shared Code before the unique code
     Code Unique to First Derived Class
     Shared Code after the unique code
    
     Shared Code before the unique code
     Code Unique to Second Derived Class
     Shared Code after the unique code
    

提交回复
热议问题