Give a class an object instance

Hi there,

how to use an instance of an object inside another class as instance variable?

Like this?

class A .h
{
 A(B instance)
 B myObjectInstance
}

class A .cpp
{

 A::A(B instance)
{
 myObjectInstance = instance;
}

void A::test()
{
 myObjectInstance.someMethod();
}

}


class B
{
 void someMethod();
}

I know I can use an object instance in a method like this, but it does not work as instance variable:

void test(const B& obj)
{
 obj.someMethod();
}

So how to give the constructor of A an instance of B and use B anywhere in class A?

Thank you!

If you want to store a reference ('&') to the B instance, then you need to pass the instance to the A object during construction. Actually before construction. Use an initializer list to do this:

class A
{
    B& myObjectInstance;

    A(B& instance) : myObjectInstance(instance)
    {
        // constructor code
    }
};

Your wording is not very clear. “Does not work” is not a meaninglful combination of words in a technical forum.

If you want to store an object of one class inside another class, then it is just

class B
{
public:
  void someMethod() {}
};

class A
{
   B myObjectInstance;

public:
   A (const B &instance) : myObjectInstance(instance)
     {}

  void test();
};

void A::test()
{
  myObjectInstance.someMethod();
}

In this case you are storing a copy of the object passed through the constructor parameter.

asuryan:
Hi there,

how to use an instance of an object inside another class as instance variable?

Like this?

class A .h

{
A(B instance)
B myObjectInstance
}

class A .cpp
{

A::A(B instance)
{
myObjectInstance = instance;
}

void A::test()
{
myObjectInstance.someMethod();
}

}

class B
{
void someMethod();
}




I know I can use an object instance in a method like this, but it does not work as instance variable:



void test(const B& obj)
{
obj.someMethod();
}




So how to give the constructor of A an instance of B and use B anywhere in class A?

Thank you!

When you have a problem, give a detailed description of that problem. Is compilation failing? Post the error. Is it running incorrectly? Tell us what it’s doing and what you expected it to do.

In this case, I believe it’s because all class members are private by default. That means they can only be accessed by the class’s functions, and not any external code.

Always mark explicitly which parts of your class members are public and which are private, like Motmorency did.