1

Is it possible to make a child member of the same class in C++? Something like

class A
{
public:
  int i;
  A child;
};

Thanks in advance.

alex555
  • 1,676
  • 4
  • 27
  • 45

4 Answers4

5

This requires the infinite type, which is not possible in C++.

You need extra indirection, for example through a pointer:

#include <memory>

class A {
public:
    int i;
    std::unique_ptr<A> child;
};
  • Worth mentioning also the possibility of `std::shared_ptr` and `std::weak_ptr`, as well as a bare pointer or a reference, which might still be relevant in some cases. See also: https://stackoverflow.com/questions/63365537/c-instance-of-same-class/63365597#63365597 – Amir Kirsh Aug 12 '20 at 10:06
1

You cant have a member object of the same type ( otherwise the class would go infinitely large) but your class can have a pointer that points to an object of the same type. i.e,

class A
{
public:
 int i;
 A *child;
};

is possible.

jester
  • 3,491
  • 19
  • 30
1

You can do it only for static data members because it is allowed that declarations of static data members had incomplete types. You may not do the same with non-static data members. You can only define them as pointers to the class itself.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Directly - no. How big would that structure be?

But there is another way, you can contain a pointer to your class:

class A
{
public:
    int i;
    A * child;
};

If you want to implement it more clearly, you may use std::unique_ptr or std::shared_ptr instead of C-style pointer, depending on your needs.

But everything depends on what you want to achieve. If you're implementing your own data structure - such as list, tree etc., this is a good approach. But otherwise I'd think, if such dependency is really required and if such solution isn't some kind of design flaw.

Spook
  • 25,318
  • 18
  • 90
  • 167