ryan
ryan

Reputation: 645

How to instantiate an object to another class in the constructor of a class? C++

Is it possible to construct an object to class2 in the constructor of class1 that can be used in all the functions in class1?

EXAMPLE:

class c1 {

//Constructor for c1
c1() {

//Object to class c2 that I want to be able to use in all the c1 functions
c2 c2Object;

}

void randomFunction() {

c2Object.randomFunctioninC2();

}


}

Upvotes: 0

Views: 68

Answers (1)

You are looking for a member variable. Notice that the variable is declared in the class itself, not in the constructor. If it was declared in the constructor, it would be an ordinary local variable in the constructor (and therefore it would only exist inside the constructor).

class c1 {
    c2 c2Object;

    void randomFunction() {
        c2Object.randomFunctioninC2();
    }
};

Upvotes: 1

Related Questions