Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I instantiate an object inside of a C++ class?

For C++ learning purposes, I have the files class1.h, class1.cpp, class2.h and class2.cpp. I would like to instantiate an object named class1Obj inside class2. Where and how do I instantiate this object? Do I instantiate classObj inside the class2 constructor?

In the past I have created a pointer to a class, which worked well for that time, but I think a pointer is not the route I should take this time because the classObj will only be used inside class2.

like image 686
dottedquad Avatar asked Nov 06 '12 10:11

dottedquad


1 Answers

class class1
{
   //...
};

class class2
{
   class1 member; 
   //...
};

In class2 ctor, you can initialize member in the constructor initialization list.

class2::class2(...)
: member(...)
{
   //...
}
like image 99
Armen Tsirunyan Avatar answered Oct 04 '22 20:10

Armen Tsirunyan