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

12,252

Solution 1

class class1
{
   //...
};

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

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

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

Solution 2

Well how did you create a pointer in the past? Presumably, you did something like this:

class class2
{
  public:
    class2()
    {
      class1Pointer = new class1();
    }
    // Destructor, copy constructor/assignment, etc...
  private:
    class1* class1Pointer;
};

Now you want to do exactly the same but this time you don't want a pointer to class1, you want a class1 itself:

class class2
{
  public:
    class2() {}
    // Destructor, copy constructor/assignment, etc...
  private:
    class1 class1Obj;
};

The object will be default initialized when your class2 object is created. If your class1 constructor should take some arguments, use an initialization list:

class class2
{
  public:
    class2() : class1Obj(1, 2, 3) {}
    // Destructor, copy constructor/assignment, etc...
  private:
    class1 class1Obj;
};

Solution 3

Instantiate a class inside a class :

#include <iostream>
using namespace std;



class Foo 
{
 public:
     Foo(int i) 
     {

     }  
};

class Bar  
{     
  Foo i;  //<--- instantiate a class inside a class ----
  public:

  Bar() : i(1)  //<--- instantiate a class inside a class ----
  {

  }  
};





int main(void)
{


  Bar b;




  cout<<" \nPress any key to continue\n";
  cin.ignore();
  cin.get();

   return 0;
}

Solution 4

It depends on your Class1. If its constructor accepts some parameters, then you must initialize it explicitly in Class2 constructor or in initialization list.

Class2 {
public:

    class2() {
        //Here m_class1Obj will be instantiated
        m_class1Obj = Class1(/*some params*/);
    }

private:
    Class1 m_class1Obj;
};

Or

Class2 {
public:

    class2() : m_class1Obj() {}

private:
    Class1 m_class1Obj;
};
Share:
12,252
dottedquad
Author by

dottedquad

Updated on June 21, 2022

Comments

  • dottedquad
    dottedquad almost 2 years

    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.

  • john
    john over 11 years
    Except you aren't showing initialization, you are showing assignment.
  • Armen Tsirunyan
    Armen Tsirunyan over 11 years
    -1 for not using constructor initialization list. What if M_class1Obj were const? How would you do it then?
  • besworland
    besworland over 11 years
    Constructive critics. Updated.