Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 554
kapesu8 Avatar asked Oct 27 '25 13:10

kapesu8


1 Answers

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

like image 51
Andrew Avatar answered Oct 30 '25 03:10

Andrew