3

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); 
3
  • 3
    Show us the header files Commented Dec 3, 2011 at 20:43
  • 4
    It sounds like you're not using include guards, which have nothing to do with inheritance. See en.wikipedia.org/wiki/Include_guard . Commented Dec 3, 2011 at 20:43
  • @AntonGolov you should post your comment as an answer for others to see in case they encounter the same error. Commented Dec 3, 2011 at 20:54

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

0

One could also use #pragma once in this situation. #pragma once has some advantages over the include guards: it contains less code, avoids name clashes and sometimes takes less compile time.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.