I’m just beginning with C++, so I’m looking some code to learn. I found this code fragment in a Breakout game.
#pragma once
#include "force.hpp"
#include "brick.hpp"
#include <vector>
class Painter;
class Ball;
class Wall
{
public:
enum { ROWS_COUNT = 16,
COLS_COUNT = 8 * 3 };
enum { WIDTH = ROWS_COUNT * Brick::WIDTH,
HEIGHT = COLS_COUNT * Brick::HEIGHT };
Wall();
void draw(Painter &) const;
Force tick(const Ball &);
public:
typedef std::vector<Brick> Bricks;
Bricks bricks_;
};
The only part that I don’t understand is the following:
class Painter;
class Ball;
What’s mean that two “class [name];”? In the source code there are differents Painter.cpp, Painter.hpp, Ball,hpp, Ball.cpp.
This mean some kind of include?
Those are forward declarations, which can be used to say that a name exists, but no definition of it exists at this time yet, but I want to use the name.
Note that in the class, it only uses pointers and references to
PainterandBall. When using forward declarations, this is completely fine, but if you put in code that depends on knowledge about the internals of thePainterorBallclasses (like calling a function or using a member variable of the class), then you’d have to include the actual class declarations.For example, notice how the header
#includes thebrick.hppheader, because the class has anstd::vector<Brick>container, that stores copies ofBrickobjects, and needs to knowsizeof(Brick). The header also usesBrick::WIDTHandBrick::HEIGHT.Another common use case for forward declarations is to fix the circular dependency problem.