How to call a parent class function from derived class function?

后端 未结 7 1182
自闭症患者
自闭症患者 2020-11-22 06:16

How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is deri

7条回答
  •  春和景丽
    2020-11-22 07:13

    Given a parent class named Parent and a child class named Child, you can do something like this:

    class Parent {
    public:
        virtual void print(int x);
    };
    
    class Child : public Parent {
        void print(int x) override;
    };
    
    void Parent::print(int x) {
        // some default behavior
    }
    
    void Child::print(int x) {
        // use Parent's print method; implicitly passes 'this' to Parent::print
        Parent::print(x);
    }
    

    Note that Parent is the class's actual name and not a keyword.

提交回复
热议问题