So I would like to create a class that can have an object which type is itself. Something like this:
class foo {
foo Avalue = foo();
foo Bvalue = fo
No. That is fundamentally impossible. Think about it: the class would have infinite size (well, unless it has no other members, I suppose, but then what does it do?), and no provable definition/identity.
You can store pointers to other foo
objects, though. This works as long as not every foo
has a member pointer that does point to another foo
, or if the references form a cyclic dependency. Either way the compiler won't be diagnosing this in the way that it must with your attempted solution, but you can find trouble at runtime if you're not careful.
Your code suggests you're implementing a tree. This is the reason (well, one among a few, I suppose) that std::map
, which is usually a tree, creates its nodes dynamically and links them with pointers. As does every linked list implementation.
The problem with that is that the foo
inside foo
would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain a foo
which would contain...