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

前端 未结 3 1516
囚心锁ツ
囚心锁ツ 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:27

    In Java, all methods are virtual by default, unless you declare them final. In C++ it's the other way around: you need to explicitly declare your methods virtual. And to make them pure virtual, you need to "initialize" them to 0 :-) If you have a pure virtual method in your class, it automatically becomes abstract - there is no explicit keyword for it.

    In C++ you should (almost) always define the destructor for your base classes virtual, to avoid tricky resource leaks. So I added that to the example below:

    // GameObject.h
    
    class GameObject
    {
    public:
        virtual void update() = 0;
        virtual void paint(Graphics g) = 0;
        virtual ~GameObject() {}
    }
    
    // Player.h
    #include "GameObject.h"
    
    class Player: public GameObject
    {
    public:
        void update();
    
        void paint(Graphics g);
    }
    
    // Player.cpp
    #include "Player.h"
    
    void Player::update()
    {
         // ...
    }
    
    void Player::paint(Graphics g)
    {
         // ...
    }
    

提交回复
热议问题