Deepak B
Deepak B

Reputation: 2335

Inheritance in C++: Error C2011

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);

Upvotes: 3

Views: 2700

Answers (3)

AleC
AleC

Reputation: 699

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.

Upvotes: 0

Bojan Komazec
Bojan Komazec

Reputation: 9526

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.

Upvotes: 4

Komi Golov
Komi Golov

Reputation: 3471

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.

Upvotes: 5

Related Questions