-2

I want my class to have an attribute which would be an instance of the same class, something like this:

class Person
{
public:
    std::string name;
    Person nested;
};

Here my IDE (Visual Studio 2022) says incomplete type is not allowed. Is it possible to have an instance of the same class inside a class in C++? How can I implement this?

Kaiyakha
  • 1,463
  • 1
  • 6
  • 19
  • 1
    What would be the size of an object that contains a string and an object that contains a string and an object that contains a string and an object that [...] ? – molbdnilo Apr 30 '22 at 08:47
  • @molbdnilo recursion moment, didn't think about that, sorry – Kaiyakha Apr 30 '22 at 08:48
  • @molbdnilo what if I create a child class which would extend its parent with attributes which are instances of the parent class? – Kaiyakha Apr 30 '22 at 08:49
  • 1
    This sounds like an xy-problem. What is the problem you are actually trying to solve? – G.M. Apr 30 '22 at 08:51
  • @G.M. it's rather about learning c++, not about solving certain problems – Kaiyakha Apr 30 '22 at 08:54
  • Why don't you just have a `Person*`. Since the size of `Person*` is known it will work OK. How this would be used is an other question – Lala5th Apr 30 '22 at 09:06

1 Answers1

1

Person nested; will have default value, which is empty Person
So when you create Person, inside it automatically will be created Person, inside which will be created Person and so on

to avoid this, you need to use pointer

class Person
{
public:
    std::string name;
    Person* nested;
};

source: https://mrcodehunter.com/incomplete-type-is-not-allowed/

Rigorich
  • 74
  • 3