Making one header to be needed for several classes inclusion - c++

I have a number of classes and they are quite close to each other like
class A
{
//code
};
class B
{
A* field;
//code
};
class C: public B
{
//code
};
And so on.
And I want to place them in a separate headers (A.h, B.h...) but to avoid adding every one of this header to projects I need a header like myLib.h, that will be just one needed header to include all the classes that I have wrote. Ho do I achieve it?
Also I think not to use #pragma once; and to make it working
#ifndef _MY_LIB_H
#define _MY_LIB_H
#endif
Where should I place it? In every header?
I've tried doing it like
class A;
class B;
...
in myLib.h
but then adding myLib.h to main.cpp is not enough to use A or B objects there. Also, in B.h that
#inlude myLib.h
void someMethod()
{
//field is instance of A
this.field.otherMethod();
}
causes an error because methods of A are declared in A.h, not in myLib.h.
Sorry for long and tangled question.

You should use a separate include guard in each of A.h, B.h, C.h:
// Note: not a good name for a guard macro (too short)
#ifndef _A_H
#define _A_H
// definition of A
#endif
And then MyLib.h becomes simply:
#include<A.h>
#include<B.h>
#include<C.h>
Of course each of your headers should manually include as many of the others as required so that it can stand alone (e.g. C.h would need to include B.h so that the code compiles if someone includes C.h directly).
In some cases you will not need to have one header include another because a forward declaration is enough -- for example in B.h, where an A* member is declared:
#ifndef _B_H
#define _B_H
class A;
class B
{
A* field;
};
#endif

Besides using the pattern
#ifndef _A_H
#define _A_H
... Stuffs
#endif
in each header, I always add
#ifndef _A_H
#include <A.h>
#endif
#ifndef _B_H
#include <B.h>
#endif
....
to other headers, like myLib.h. This considerably improves the speed of compilation because compiler does not need to load and scan the low level headers if they are already scanned.
I do not add this to my cpp files, because the number of headers in cpp is typically reasonable, while it mich more difficult to track relations between headers.

Related

Proper use of declaring objects in header files

I am working on a clock display assignment and my professor wants us to use two classes, NumberDisplay and ClockDisplay. So in total I have two header and three cpp files. When I implemented the first part of the assignment using just the first class everything was fine. I noticed though that my professor wants us to declare a NumberDisplay object inside our ClockDisplay header. I figured just declaring like normal would work like this NumberDisplay hours = NumberDisplay(24); however I am not able to access the information unless I include the NumberDisplay.h file for my ClockDisplay.h. When I do that however I am assuming my errors are due to using #include <NumberDisplay.h> in both my NumberDisplay.cpp and my ClockDisplay.cpp. I just would like to know the proper way to structure my files so that I can properly create NumberDisplay objects in my ClockDisplay header file and then use said objects in my ClockDisplay cpp file.
You can #include "NumberDisplay.h" within ClockDisplay.h. This will allow you to use NumberDisplay objects within your ClockDisplay's class declaration.
As a side note, be sure to use include guards for your headers. This will prevent the header from being included multiple times during compilation. Use #pragma once or
#ifndef NUMBERDISPLAY_H_
#define NUMBERDISPLAY_H_
...
#endif // NUMBERDISPLAY_H_
As user Sean Monroe pointed out about using header or include guards; this may not always be the full answer. This will help in many cases to fix your current problem but if you are not careful you can become a victim of circular includes.
Before I mention anything about that I will briefly describe the differences between #include <someheader.h> and #include "someheader.h". The first one will look where most of your system, os, and compiler and standard libraries files are located through the use of system environment variables that are setup by default through your IDE. The later will look in any immediate directories that are setup in the include paths for the current project with the root path being where the code lives when it is created if working in Visual Studio; other IDE's will more than likely be different, but the concept is still the same.
On circular includes: sometimes having header guards alone is not enough. Take for example:
file a.h
#ifndef A_H
#define A_H
#include "b.h"
class A {
private:
B b;
public:
explicit A( const B& b ) { ... }
};
#endif
file b.h
#ifndef B_H
#define B_H
#include "A.h"
class B {
public:
explicit( A* pA ) { ... }
};
#endif
Here this would generate a circular include and this is something that is very important to be aware of. Regardless of which class A or B you try to create an object of in some other file, namespace, class or function the compiler will try to construct the first class and in order to do so it needs to construct the second class however when trying to construct the second class to complete the first class it goes back and tries to construct the first class again since the next requires the first which is an incomplete object and visa versa. This is not exactly a circular include per say but it is a circular infinite recursion of dependencies of incomplete classes. You can read this Q/A for more information: Resolve Circular Dependencies.
Sometimes it is not enough to just include the appropriate header of one class into the header of another; sometimes you may need to just declare a class prototype and or forward declaration in a class's header then include the header file within that class's cpp file. But this will usually work most often with pointers or references but not local copies since pointers and references are addressed by memory location that have a fixed size in memory. Example:
file A.h
#ifndef A_H
#define A_H
class B;
class A {
private:
B* pB;
public:
explicit A( const B& b );
};
#endif
file A.cpp
#include "A.h"
#include "B.h"
A::A( const B& b ) { ... }
file B.h
#ifndef B_H
#define B_H
#include "A.h"
class B {
public:
B(){ ... }
/*param type*/ someFunc( A* pA ) { /* do something with pA */ }
};
There are more problems than what are discussed here but you can read about them in some of the other answers to the same link that I provided above.

#include cyclic dependency error

I have code structure like this:
resource.h:
#include"a.h"
#include"b.h"
#include"c.h"
a.h:
#ifndef __A__
#define __A__
#include"resource.h"
class B;
class A{
//something uses B
};
#endif
b.h:
#ifndef __B__
#define __B__
#include"resource.h"
class A;
class B{
//something uses A
}
#endif
c.h:
#ifndef __C__
#define __C__
#include"resource.h"
class A;
class B;
class C{
//something uses A and B
};
#endif
The problem is the following: VS2010 tells me that in c.h, line #include"resource.h" causes "resource.h" includes itself.
However, the codes are able to compile and performed as expected. So I am wondering what causes this error intellisense in VS and if there is anyway to remove it.
P.S: I am compiling with VS and there is no compiling error.
You don't have a header guard on resource.h:
#ifndef __RESOURCE__
#define __RESOURCE__ 1
#include "a.h"
#include "b.h"
#include "c.h"
#endif
However, double underscores aren't recommended, as they're reserved for the implementation. So I would use {PROJECTNAME}_RESOURCE_H. This will also prevent header guard collisions with other projects that don't do this.
Seeing that you're using Visial Studio, I would reccomend you don't use header guards and instead use #pragma once if your project isn't going I be compiled with gcc.
You can use #pragma once preprocessor to make resource.h to be included only once in compilation.
c.h includes resource.h which then itself includes a.h and b.h which each include resource.h again.
You are creating cyclic dependency.
in resource.h you have included a.h , b.h and c.h which is not required.
class files needs resource, resource file does not need class information.

Why declare the class that you included as a header file?

Why declare the class that you included as a header file?
#include "TreeCallObj.h"
#include "TreeDevObj.h"
#include "TreeDevCallObj.h"
class TreeCallObj; //what is the purpose of this line ?
class TreeDevObj; //what is the purpose of this line ?
class TreeDevCallObj; //what is the purpose of this line ?
class Apple
{
public:
...
private:
...
}
Consider this:
//a.h
#ifndef A_H
#define A_H
#include "b.h"
class A
{
B* b;
};
#endif
//b.h
#ifndef B_H
#define B_H
#include "a.h"
class B
{
A* a;
};
#endif
Now you try to include one of the files in a different one, say you #include "a.h".
The compiler will parse it as:
#ifndef A_H
#define A_H
fine - A_H isn't defined
#include "b.h"
try to paste the contents:
#ifndef B_H
#define B_H
ok, since B_H isn't defined
#include "a.h"
this will not define A, because A_H is defined. So next, we have
class B
{
A* a;
};
which will lead to an error, because A wasn't defined or declared before the use.
The forward declaration fixes this.
Of course, the best solution to this is to not include at all (unless you absolutely have to).
What is the purpose of this line?
Ideally nothing. It's superfluous.
However, as #Luchian Grigore pointed out, there may be such a badly-designed code that due to the incorrect use of include guards and cross-includes, the forward declarations may be necessary.
If in files there is definition of classes, so, forward declaration is unnecessary in normal cases.
No reason at all. You need to do one or the other, depending on the situation, but not both.
As it stands, there's no need.
However, this may have evolved historically: At some point, an incomplete type may have been enough:
class Foo;
struct Gizmo
{
void f(Foo);
};
Then, at a later point, the author decided she needed the complete type:
#include "Foo.hpp"
class Foo;
struct Gizmo
{
void f(Foo);
Foo x;
};
The original code may just have been amended with the now-necessary header inclusion...
I would guess there's some history to this. Orginally the coder tried not to include the header files and used forward declarations instead. Then as the code expanded they found they needed the header files after all, but didn't bother to deleted the forward declarations.
As others have said there's no purpose to having a forward declaration after the class declaration.
I notice that your header does not have guards against multiple inclusion. Also it is possible that some of the included other headers (headers usually have such guards) included that header back. As result it did not compile. So someone added forward declarations to fix the wrong bug.
If your header files are correct i see no point in declaring because they should already declared in header

Include guard style, C++

I have a .h file which contains several class definitions. I'd like to use C++'s include guards in this file; however, I was wondering which way of using the include guards is considered proper/correct?
One guard protecting everything
#ifndef FOO_BAR
#define FOO_BAR
class Foo
{
};
class Bar
{
};
#endif
or multiple separate guards.
#ifndef FOO
#define FOO
class Foo
{
};
#endif
#ifndef BAR
#define BAR
class Bar
{
};
#endif
They are include guards, preventing double inclusion of files. So they should be defined once per file, not per class or function or whatever.
Have you considered to use #pragma once ? Most modern compilers support it.
Is #pragma once a safe include guard?

Using forward reference

I have a circular header problem that is different from most of the ones already asked on here. I have two classes that depend on each other but not as members so don't run into the problem of the compiler not being able to calculate the class's sizes. So I'm able to use a forward-declaration to break the cycle.
However, I don't want the client to have to include both these headers to use my classes. The headers should be self-contained so the user doesn't need to be aware of this dependency. Is there some way to do this?
Edit: the tricky part is that A and B must be defined header-only.
In header A.hpp
#ifndef A_HPP
#define A_HPP
#include "B.hpp"
struct A
{
B foo() { ... }
};
#endif
In header B.hpp
#ifndef B_HPP
#define B_HPP
struct A;
struct B
{
void bar()
{
A a = A();
...
}
};
#endif
In main.cpp
#include "B.hpp"
B().bar(); // error: 'a' uses undefined class 'A'
Header B.hpp
#ifndef B_HPP
#define B_HPP
struct A;
struct B
{
void bar();
};
#endif
Source B.cpp
#include "A.hpp"
void B::bar()
{
A a;
}
EDIT. So, if you want header-only implementation, then use AndreyT solution.
If both headers contain code that requires the other type to be complete, then in general case it cannot possibly be implemented by self-contained headers.
In your specific example (which is too simple to be representative), you can simply move the definition if B::bar to A.hpp:
inline void B::bar()
{
A a = A();
...
}
But, of course, having methods of B defined in A.hpp doesn't look very elegant.
If the "inlinedness" of B::bar is important to you, the "industrial" solution would involve placing the definition of B::bar into an additional header file B_aux.hpp. When you include the headers, you should include the "aux" ones after all "normal" ones are included, i.e. in main.cpp you'd have
#include "A.hpp"
#include "B.hpp"
#include "C.hpp"
...
#include "B_aux.hpp"
...
But this is, obviously, not a "self-contained" approach.
Just add a #include "A.hpp" to the bottom of B.hpp. You'll still have a circular include, but now it won't hurt anything.
Usually circular includes are a sign that the two types are closely related, and that could mean that they are a single component. If that is the case, then just merge the two headers into a single header for the component, with the type declarations first and the member function definitions at the end, when both types have been fully defined.