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)
{
// ...
}
In C++ you use the keyword virtual on your routines, and assign =0;
into them. Like so:
class GameObject {
public:
virtual void update()=0;
virtual void paint(Graphics g)=0;
}
Having a virtual method with a 0
assigned into it automagically makes your class abstract.
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).