Hi Guys :),
I am facing class redifinition error when I include a base class .h file in two different derived class .h files and then include these two header files in my .cpp file.
Base class header file : animal.h
Derived class header files : cat.h, dog.h
cpp file that includes above two files : test_animal.cpp
I understand (please correct me if I am wrong) that the class redifinition error is coming because each header file includes the animal.h header file and when these two header files (cat.h & dog.h) are included in a third program, the redifinition issue comes.
1) How do we overcome these kind of issues where in the requirement says that we need to include same header file in multiple header files and then use two or more of these header files in a program.
Base class header file : animal.h
Derived class header files : cat.h, dog.h
cpp file that includes above two files : test_animal.cpp
animal.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#ifndef _ANIMAL_INSTANCE
#define ANIMAL_INSTANCE
class Animal
{
public:
unsigned int nLegs;
Animal(unsigned int p_nLegs);
unsigned int getLegs();
virtual void speak() = 0;
};
#endif
|
cat.h
1 2 3 4 5 6 7 8 9 10 11 12
|
#ifndef CAT_H_
#define CAT_H_
#include "animal.h"
class Cat : public Animal
{
public:
Cat(unsigned int p_nLegs);
virtual void speak();
};
#endif
|
dog.h
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#ifndef DOG_H_
#define DOG_H_
#include "animal.h"
class Dog : public Animal
{
public:
Dog(unsigned int p_nLegs);
virtual void speak();
};
#endif
|
test_animal.cpp
1 2 3 4 5 6 7 8 9 10
|
#include "animal.h"
#include "cat.h"
#include "dog.h"
int main()
{
Cat cat(4);
Dog dog(20);
return 0;
}
|
Thanks :)
P.S. : Please note that I have given definitions for the above .h files in respective .cpp files.