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
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)
{
// ...
}