Alex Rivera | Logout

Declare an object even before that class is created

Asked 2008-09-22T06:04:39.007
12

Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class.

Edit
Report

1 Answer

44

You can't do something like this:

class A {
    B b;
};
class B {
    A a;
};

The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A!

You can, however, do this:

class B; // this is a "forward declaration"
class A {
    B *b;
};
class B {
    A a;
};

Declaring class B as a forward declaration allows you to use pointers (and references) to that class without yet having the whole class definition.

answered 2008-09-22T06:08:41.930

Your Answer