Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare an object even before that class is created

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.

like image 697
Matt Pascoe Avatar asked Sep 22 '08 06:09

Matt Pascoe


People also ask

Can you declare an object of the same class type inside a class?

No, the main method only runs once when you run your program. It will not be executed again. So, the object will be created only once.

How are objects of a class declared?

Creating an Object Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Can a class create an object of itself?

A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type. For example, following program works fine.

Is used to initialize aspects of a class before any objects of the class are created?

A constructor is a member function of a class that initializes objects of a class.


2 Answers

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.

like image 130
Greg Hewgill Avatar answered Oct 22 '22 00:10

Greg Hewgill


You can't declare an instance of an undefined class but you can declare a pointer to one:

class A;  // Declare that we have a class A without defining it yet.

class B
{
public:
    A *itemA;
};

class A
{
public:
    B *itemB;
};
like image 42
Adam Pierce Avatar answered Oct 22 '22 02:10

Adam Pierce