I'm trying to display Tiles of different colors on a screen in C++ through inheritance. I have a base class called Tile and then two derived classes called GreenTile and VanillaTile.
In my main, when I create only a GreenTile or only a VanillaTile by creating either a GreenTile object or a VanillaTile object, it works properly:
GreenTile greenTile(0,0);
greenTile.show(screen);
The problem is, when I create both GreenTile and VanillaTile objects and try to display both I'm getting "error C2011: 'Tile' : 'class' type redefinition".
GreenTile greenTile(0,0);
VanillaTile vanillaTile(0,0);
greenTile.show(screen);
vanillaTile.show(screen);
What you are running into has nothing to do with inheritance: it is a matter of using so-called include guards. Note that these will generally only protect against multiple definition errors issued by the compiler, not by the linker.
In your source code where main is (let's say that is main.cpp), you probably have
#include "GreenTile.h" // (1)
#include "VanillaTile.h" // (2)
and in each of these headers you have
#include "Tile.h"
If your Tile.h doesn't have include guards you're including twice definiton of the class Tile. Your Tile.h should look like this:
#ifndef TILE_H
#define TILE_H
class Tile
{
...
};
#endif
Preprocessor copies the content of headers (1) and (2) at the beginning of main.cpp. With them it copies twice Tile.h but because of these guards only content of the first copy remains. This way compiler doesn't complaint as it sees a single definition of class Tile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With