How do I instantiate an object inside of a C++ class?
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;
};
dottedquad
Updated on June 21, 2022Comments
-
dottedquad almost 2 years
For C++ learning purposes, I have the files
class1.h
,class1.cpp
,class2.h
andclass2.cpp
. I would like to instantiate an object namedclass1Obj
insideclass2
. Where and how do I instantiate this object? Do I instantiateclassObj
inside theclass2
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 insideclass2
. -
john over 11 yearsExcept you aren't showing initialization, you are showing assignment.
-
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 over 11 yearsConstructive critics. Updated.