C++ Parent class calling a child virtual function

前端 未结 7 871
半阙折子戏
半阙折子戏 2021-02-13 22:34

I want a pure virtual parent class to call a child implementation of a function like so:

class parent
{
  public:
    void Read() { //read stuff }
    virtual vo         


        
7条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 23:20

    It's because your call is in the constructor. The derived class will not be valid until the constructor has completed so you compiler is right in dinging you for this.

    There are two solutions:

    1. Make the call to Process() in the derived class's constructor
    2. define a blank function body for Process as in the following example:
    class parent
    {
      public:
        void Read() { //read stuff }
        virtual void Process() { }
        parent() 
        {
            Read();
            Process();
        }
    }
    

提交回复
热议问题