-3

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?

Omar Mneimneh
  • 426
  • 5
  • 13

2 Answers2

-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
Susmit Agrawal
  • 3,280
  • 2
  • 10
  • 25
-1

Yes, you can use pragma or #ifndef

#ifndef _AUTOMOBILE_H
#define _AUTOMOBILE_H
//...
#endif  
codeHero
  • 7
  • 1
  • 4
    Names 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