I’ve got class Figure in my header “figure.h”:
class Figure
{
Color color;
std::string position;
...
};
and I want to define a class King in header “king.h”. So in king.h I do
#include "figure.h", and write for ex:
class King : public Figure
{
char type;
bool checkIfTypeIsValid(std::string);
...
};
But this doesn’t seem to work, as King doesn’t recognize Figure… What should I do? And is it smart to have different headers for different inherited classes, or just lump them together in “figure.h”? Because I’ll have a Queen, Bishop, etc. figures as well, which will make quite a lot of headers and impl. files..
First: you cannot derive from an unknown, or even a partially known
class. In order to define
King, you must first includeFigure.h(supposing
Kingis defined in a different file).More generally, as to how to organize the code, there is no one
definitive answer. Personally, in the one particular case (where the
number of derived classes is well defined and strictly bound), I’d
probably cut corners and define all of them in
Figure.h, but there arevery good arguments for using a separate header for each—if
nothing else, you don’t have to include the headers for the individual
figures except in files where they are created. Another solution would
be to use factory functions for the figures, and define the derived
classes in the source file which implements the factory functions.