Diogenis Siganos
Diogenis Siganos

Reputation: 797

C++: is it possible to late-initialize a class member function?

I have the following code:

#include <iostream>

class First {
    public:
        Second* x;
        void make_value(Second* sec_);
        First() {
            // Initialization
        }
};

class Second {
    public:
        First* y;
        Second() {
            // Initialization
        }
};

void First::make_value(Second* sec_) {
    x = sec_;
}

void main() {
    fir = new First();
    sec = new Second();
    fir->make_value(sec);
}

The two classes each have a member variable of the other class, which does not work for obvious reasons.

My question is whether or not there is a way to late-initialize variable x after class Second has been initialized. If not, what alternatives are there?

Upvotes: 0

Views: 237

Answers (1)

Alexander Kondratskiy
Alexander Kondratskiy

Reputation: 4275

For any uses where the compiler doesn't need the definition of a class, a forward declaration will suffice. Pointers and references to types do not require a definition.

class Second; // forward declare

class First {
    public:
        Second* x;
        void make_value(Second* sec_);
        First() {
            // Initialization
        }
};

class Second {
    public:
        First* y;
        Second() {
            // Initialization
        }
};

void First::make_value(Second* sec_) {
    x = sec_;
}

Upvotes: 5

Related Questions