How to allow a class to know about another?

Not sure how to setup the includes (if that's how it's done) to allow one class to know about another class.

Specifically I want class A to contain an array of class B objects as a private data member and to initialize this array in A's default constructor.

A.h:
1
2
3
4
5
6
7
8
9
#ifndef A_H
#define	A_H
class A {
public:
    A();
private:
    B anArray;
};
#endif	/* A_H */ 

A.cpp:
1
2
3
4
5
#include "A.h"

A::A() {
    anArray = new B[10];
}

B.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef B_H
#define	B_H
using namespace std;

class B {
public:
    B();
    string getName() const {return name;}
    int getNumber() const {return number;}
private:
    string name;
    int number;
};
#endif	/* B_H */ 

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

B::B() {
    name = "";
    number = 0;
}

main.cpp:
1
2
3
4
5
6
7
8
9
#include "A.h"
#include "B.h"
using namespace std;

int main(int argc, char** argv) {
    A thingA = new A();
    B thingB = new B();
    return 0;
}
Last edited on
You can put any necessary includes in header files. For example by putting
 
#include "B.h" 

between lines 2 and 3 of "A.h". The #include is required because the compiler requires a complete definition of class B so that it knows how much space A will occupy and this is because you declared anArray as an object of type B.
Which, by the way, is wrong for what you seem to be trying to do.
For the constructor of A to work as written you need to make anArray a pointer to B ie. change line 7 to read
 
    B* anArray;

This change will make the #include unnecessary and you can replace it with just a forward declaration of class B which you should put before line 3.
 
class B;

Storing a pointer to B makes it unnecessary for the compiler to know the full definition of B because the amount of space the pointer requires is independent of what it points to (at least in general).
Also, don't forget to delete anArray, for example by creating a destructor for class A like this:
1
2
3
4
A::~A()
{
    delete[] anArray;
}

And finally a new does not return an object of the type it creates but a pointer to the object it creates which you have to make sure is deleted at some later point when you're done with the object it points to. So your main.cpp should be:
1
2
3
4
5
    A* thingA = new A();
    B* thingB = new B();
    // do something with thingA and thingB
    delete thingA;
    delete thingB;
So your main.cpp should be:
1
2
A thingA;
B thingB;
Topic archived. No new replies allowed.