Let's say we have a parent class with header parent.h
and 2 child classes child1.h
and child2.h
, since they both inherit from parent, both header files should include parent.h
. Including child1.h
and child2.h
in another file will result of a duplicate definition of the parent class. What is the best way to avoid this? Is using #pragma once
a good practice, or are there other ways to fix this?
Asked
Active
Viewed 104 times
-3
![](../../users/profiles/8709838.webp)
Omar Mneimneh
- 426
- 5
- 13
2 Answers
-1
This is the exact reason why #ifndef
is used as a check in header files.
For example, your `parent.h' may have:
#ifndef PARENT_H
#define PARENT_H
.... //Your header definition
#endif
Then, in child1.h
and child2.h
#ifndef PARENT_H
#include "parent.h"
#endif
....//Your source code
![](../../users/profiles/5533928.webp)
Susmit Agrawal
- 3,280
- 2
- 10
- 25
-
5You do not need or want that `#ifndef` in the child headers. – Oct 01 '18 at 16:39
-
so how do you do it instead? – Omar Mneimneh Oct 01 '18 at 16:43
-
1@Omar Simply have each header file have its own include guards. Other files should not know or care what the names of those guards are. – Oct 01 '18 at 16:45
-1
Yes, you can use pragma or #ifndef
#ifndef _AUTOMOBILE_H
#define _AUTOMOBILE_H
//...
#endif
![](../../users/profiles/4755729.webp)
codeHero
- 7
- 1
-
4Names like `_AUTOMOBILE_H` which begin with an underscore and an uppercase letter are reserved for the C++ implementation - you should not be creating them in your own code. Simply use `AUTOMOBILE_H` – Oct 01 '18 at 16:43