Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For a given class in C++, is it possible to have, as a private variable, a vector of objects of the same class?

Tags:

c++

vector

It has been a long time since I did any C++ programming, and I would highly appreciate it if anyone can guide me with creating a Node class that has one of its private variable a list (or vector) of objects of the Node class.

I am hoping to create a class structure as such:

class Node {
private:
  string ID;
  vector < Node > list;
public:
  Node();
  void some_Function();
};

Is this the right approach? Is it possible for a class to have one of its private members as a list of objects of the same class type?

like image 930
user2820488 Avatar asked Dec 07 '25 08:12

user2820488


1 Answers

No, you cannot.

When you define an object of type vector<T>, T must be a complete type, which it's not until the end of the class definition.

Some compilers will accept the code anyway (they'll accept a vector of some incomplete type), but it's not allowed by the C++ standard.

like image 114
Jerry Coffin Avatar answered Dec 08 '25 22:12

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!