Create object of class inside (same) class

Hello,


In C++, is it possible to create an object of a class X inside class X? For example inside a member function.


Last edited on
Here is an object of class X creating another object of class X in a member function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class X
{
public:
  X makeAnX();
};

X X::makeAnX()
{
  X aNewX;
  return aNewX;
}

int main()
{
  X firstX;
  std::cout << "Address of first X: " << &firstX << '\n';
  auto another = firstX.makeAnX();
  std::cout << "Address of another X: " << &another << '\n';
}

Thanks! what if you want to create an object of class X inside another class Y?
1
2
3
4
5
6
7
8
9
class X
{
  // some things
};

class Y
{
  X anXObject;
};
Topic archived. No new replies allowed.