A design issue. How to design when we include a header file in different header files and try to use them in a cpp file.

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.
Below are definitions for above class functions, just in case anybody wants to have a look.

animal.cpp
1
2
3
4
5
6
7
8
#include "animal.h"

Animal::Animal(unsigned int p_nLegs) : nLegs(p_nLegs) {}

unsigned int Animal::getLegs()
{
    return nLegs;
}


cat.cpp
1
2
3
4
5
6
7
8
9
10
#include "cat.h"
#include <iostream>

Cat::Cat(unsigned int p_nLegs) : Animal(p_nLegs) {}

void Cat::speak()
{
    std::cout << "\n I am a cat \n";
    return;
}


dog.cpp
1
2
3
4
5
6
7
8
9
10
#include "dog.h"
#include <iostream>

Dog::Dog(unsigned int p_nLegs) : Animal(p_nLegs) {}

void Dog::speak()
{
    std::cout << "\n Dog Dog \n";
    return;
}


Thanks :)
Your include guards should protect you from class redefinition errors, but you have an error in your include guards.

1
2
#ifndef _ANIMAL_INSTANCE
#define ANIMAL_INSTANCE  // this name must be IDENTICAL to the name being tested. 
Last edited on
Thanks @AbstractionAnon :)
Topic archived. No new replies allowed.