-2

I want to define an element that points to a same element type, something like this:

#define Foo { Foo*, ..., ... }

For example, this helps me to create a simple tree without creating any auxiliar class:

#define TreeNode std::deque(std::pair(char, TreeNode*))

TreeNode mRootNode;

However, this cannot be done, because a Foo isn't still declared when making a reference to itself in its declaration.

My question is... why the same feature is allowed when implementing it with classes? Is there another simpler way, not Object Oriented, to define my Foo?

Santiago Gil
  • 1,292
  • 7
  • 21
  • 52

1 Answers1

2

Define an element that points to a same element type in C++

A simple way to define a type that can refer to another object of the same type is to define a datastructure like this:

struct Foo {
    Foo* link;
};

No need for a macro.

This is allowed, because the Foo has been declared by the time the member pointer is declared. The rules of the language allow recursive classes, but not recursive pre-processor macros.


P.S. To clarify some confusion in the question: While classes in C++ support object oriented features, you can choose to not use those features and instead use classes just like you would use structures in C.

eerorika
  • 232,697
  • 12
  • 197
  • 326