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?
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.
You can't do this directly in a single class. But you can use CRTP, which is something that's meant specifically for something like this.
You'll have a template base class and a derived class that is templated on it's own type. The base class is then free to define other generics (like a vector
) based on the derived class. Sample code below:
#include <vector>
using namespace std;
template <typename Derived>
class Base{
vector<Derived> nodes;
public:
void TestInsert(const Derived& der){
nodes.push_back(der);
}
void TestPrintSize(){
printf("NUM %d\n", nodes.size());
}
};
class Derived1 : public Base<Derived1>{};
int main(){
Derived1 der1, der2;
der2.TestInsert(der1);
der2.TestPrintSize();
}
Yes, you can, either by using pointers or by introducing a helper class:
class NodeVector;
class Node {
private:
string ID;
NodeVector *vect;
public:
Node() : vect(new NodeVector) { }
// Don't forget other constructors & destructor because you allocate vect
};
class NodeVector {
public:
std::list< Node >;
};
Just as Jerry said. You cannot.
This is not the same as
class node {
int data;
node *next;
}
With node *, the compiler only needs to know the size of the pointer. But for vector<T>
the compiler needs to know the size of your class T
, which is not defined until the end of the class definition.