Search code examples
c++instantiation

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.


Solution

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

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

    class2::class2(...)
    : member(...)
    {
       //...
    }