Something that can happen in larger projects is that a header file for a class is included in multiple files. While this seems trivial, some compilers can run into a problem of thinking it’s multiple classes with the same name.
Luckily, C++ gives us a method to prevent this from happening, by using a built in structure – the #define statement.
Inside our circle header file we’d add a section like the following at the top and bottom.
#ifndef CIRCLE_H
#define CIRCLE_H
class Circle
{
public:
Circle();
Circle(double newRaidus);
double getArea();
double getDiameter();
double getRadius();
void setRadius(double newRadius);
private:
double radius;
};
#endif
The #ifndef
stands for if not defined. So the compiler looks to see if a variable has not been defined. If it hasn’t then #define
will define that variable.
In this case the #ifndef
, requires a #endif
statement.
These are all compiler directives and will not effect your code at all.
Another Method
There is another method. While it is not a standard, it is widely supported, and that is the #pragma once
statement. Visual Studio uses this by default.
It performs the same function, except, in some cases it can make compilation faster, and the directives is faster and easier to write.
#pragma once
class Circle
{
public:
Circle();
Circle(double newRaidus);
double getArea();
double getDiameter();
double getRadius();
void setRadius(double newRadius);
private:
double radius;
};
Preventing Multiple Class Definitions was originally found on Access 2 Learn