kapesu8
kapesu8

Reputation: 95

Defining a class member with a class type defined later in C++

Like I would want to do something like this,

class Object {
public:
World * Parent_World; //This here
Object(World * Parent_World=NULL) : Parent_World(Parent_World) {}
};

class World {
public:
Object * Objects = new Object[100];
}

That doesn't work because of the order. And I can't just simply define world earlier because I want also to have access to class Object from the World

Upvotes: 4

Views: 3994

Answers (4)

Rafael Baptista
Rafael Baptista

Reputation: 11499

forward declare your class like this:

   class World;

This works if you only use pointers to World until the World class is defined.

Upvotes: 0

Borealid
Borealid

Reputation: 98559

Andrew's answer has it right: you need a forward declaration.

It's worth noting, however, that you can't use a forward declaration when the compiler must know the size of the object. That means your World* member will work, but a World member would not.

Upvotes: 1

kol
kol

Reputation: 28728

Simply put

class World;

before

class Object { ... }

This is called forward declaration.

Upvotes: 0

Andrew
Andrew

Reputation: 24866

Make a forward declaration before Object:

class World; //Now you can use pointers and references to World
class Object {
public:
World * Parent_World; //This here
Object(World * Parent_World=NULL) : Parent_World(Parent_World) {}
};

class World {
public:
Object * Objects = new Object[100];
}

Making a forward declaration gives a compiler enough information to deal with pointers and references to the type being declared

Upvotes: 7

Related Questions