Here is the problem. I need to write header file with two classes, say class A and class B.
in class A I have function that uses object of class B and vice versa, i.e. in class B I have function that uses objects of class A.
If A declared first then there would be error that class B has not been declared.
How to deal with it? I try declare function of a class A after declaration of class B:
void classA::myfunc (classB *b);
But I got the error that function myfunc is not declared.
Experienced people in C++, what to do?
Added:
here is a good link about header
If you need a pointer to a class on a header, not the full object, just add a forward declaration, dont include the header of the pointer’s class.
I’m sure that you just use pointers to access that classes that one have a reference to another, dont you? You know, because if you use instances, you got a instance looping. Use forward declarations.
Here’s a example of how you can use forward declarations:
A.h
To illustrate how can have a class that mentions one that pointers its type:
B.h
As mentioned by Tony Delroy (Many thanks to him) You should not ALWAYS use this design. It’s provided by the C++ compiler, but its not a good practice. The best is to provide reference header, so your code would look like:
A.h
and yours forward headers like this:
B.fwd.h:
In your fwds, you should have your class forward declaration, and any typedefs that comes with it.
I’m not mentioning the
#pragma once, or the#ifndef B.H...you know they’ll be there 😀Your code would be on a standard defined by
<iosfwd>and better to maintain, specially, if they are templates.