C++: Create abstract class with abstract method and override the method in a subclass

前端 未结 3 1520
囚心锁ツ
囚心锁ツ 2021-01-01 16:18

How to create in C++ an abstract class with some abstract methods that I want to override in a subclass? How should the .h file look? Is there a .cpp

3条回答
  •  渐次进展
    2021-01-01 16:32

    The member functions need to be declared virtual in the base class. In Java, member functions are virtual by default; they are not in C++.

    class GameObject
    {
    public:
        virtual void update() = 0;
        virtual void paint(Graphics g) = 0;
    }
    

    The virtual makes a member function virtual; the = 0 makes a member function pure virtual. This class is also abstract because it has at least one virtual member function that has no concrete final overrider.

    Then in your derived class(es):

    class Player : public GameObject
    {
    public:
        void update() { }          // overrides void GameObject::update()
        void paint(Graphics g) { } // overrides void GameObject::paint(Graphics)
    }
    

    If a member function is declared virtual in a base class, it is automatically virtual in any derived class (you can put virtual in the declaration in the derived class if you'd like, but it's optional).

提交回复
热议问题