Animal
|
Mammal
/ \
TwoLegged - FourLegged
/ \
Human Lion
I have this class hierarchy, each class defined in it’s own header. Now when I include both
Human.h and Lion.h in the same place, I get a Mammal redefinition error.
error C2011: 'Mammal' : 'class' type redefinition
This because Mammal.h is included in both TwoLegged and OneLegged classes.
I’m not sure however, how I could resolve this cyclic dependency in headers, as I cannot change the class hierarchy.
Anybody care to assist?
EDIT:
Mammal header
#ifndef MAMMAL_H
#define MAMNAL_H
#include "stdafx.h"
#include "Animal.h"
class Mammal : public Animal
{
public:
Mammal::Mammal();
virtual Mammal::~Mammal();
std::string mammal_name();
int mammal_age();
int mammal_expectedlifedays();
bool mammal_hunter();
int mammal_power();
int mammal_birthrate();
bool mammal_alive();
protected:
Mammal::Mammal(const std::string& mname, int mexpectedlifedays, int mage, bool mhunter, int mpower, int mbirthrate, bool malive) : Animal(mname, mexpectedlifedays, mage,mhunter, mpower, mbirthrate, malive)
{}
private:
};
#endif
The errors given by the compiler:
error C2011: 'Mammal' : 'class' type redefinition
see declaration of 'Mammal'
error C2504: 'Mammal' : base class undefined
error C2614: 'TwoLegged' : illegal member initialization: 'Mammal' is not a base or member
Note: It’s not homework, else I would have tagged it as such.
You need to use include guards. The typical form is:
Since
#includein C++ just does a copy-paste of the text in the current file if the same header gets included twice that text will result in duplicate class definitions. What the include guard does is prevent the multiple inclusion of the same header.EDIT: The problem is that you check for definition of
MAMMAL_Hand then defineMAMNAL_H(note theNin the defined version). I always copy-paste to generate my include guards for precisely this reason.