Help declaring two classes dependent on eachother.

Hi!

I have a problem regarding two classes that are dependent on eachother in their definition. What I'm trying to acomplish is the following;

A.h:
1
2
3
4
5
6
7
8
9
10
11
12
#include "B.h"

class A
{
private:
    /* a bunch of functions and varibles here */
    int F1();
    int F2();
    ...
    
    friend int B::Func(A*);
}


B.h:
1
2
3
4
5
6
class A;

class B
{
    int Func(A*);
}


B.cpp:
1
2
3
4
5
6
7
#include "B.h"

int B::Func(A*)
{
    return(A->F1() + A->F2())
}


The problem is that B only knows that there is a class called A, but it does not know what it contains (F1, F2 ...). I cannot use class A before it's defined. How do i get around this problem? I cannot include A.h in B.h because either way I put it, either

A.h asks: What is class B?

or

B.h asks: What is class A?

I hope I've made my problem understood, ask if clarification is needed somewhere.

Thanks!

-Bobruisk
make b.cpp include a.h

You will need to add include guards to stop b.h being included twice.
AND, move any code from the header files (from one class involving the other at least) into the source files where both class definitions will be visible.
I compiled your stuff. I assume you didn't attempt to compile exactly what you posted as there are clear problems.

Anyway, it compiled with the obvious fixes:
A.h
1
2
3
4
5
6
7
8
9
10
11
12
13
#pragma once
#include "B.h"

class A
{
private:
    /* a bunch of functions and varibles here */
    int F1();
    int F2();
    //...
    
    friend int B::Func(A*);
};

B.h
1
2
3
4
5
6
7
8
#pragma once
class A;

class B
{
public:
    int Func(A*);
};

B.cpp
1
2
3
4
5
6
7
#include "B.h"
#include "A.h"

int B::Func(A* a)
{
    return a->F1() + a->F2();
}
Last edited on
Just to point out that pragma once is non-standard, whereas include guards will always work.
Just to point out that pragma once is non-standard
True, and it's not recomended for good reason. But I just wanted to get the thing to compile with minimum fuss.
Last edited on
not recomended for good reason

What reason?

I usually do this:
1
2
3
4
5
#pragma once
#ifndef BLAH_HPP
#define BLAH_HPP
...
#endif 

so that I have the portability of the include guards and the possible compile time speed improvement, etc. of the pragma approach.
Sorry, I missed to input the include guards. They are there already. I'm coding on a computer without network access so I had to type it in manually here.

The problem was that I forgot to include the A.h file in B.cpp file, which left B.cpp without the complete A-class definition.

Thanks for your help!
-Bobruisk
Topic archived. No new replies allowed.