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.
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;
};
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.
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.
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.