Can a c++ class include itself as an member?

C++

C++ Problem Overview


I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.

I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.

I plan to implement an expression tree, and a method to evaluate it in postfix order.

The problem I run into right away is:

class Node {
    char *cargo;
    Node left;
    Node right;
};

I can't declare left or right as Node types.

C++ Solutions


Solution 1 - C++

No, because the object would be infinitely large (because every Node has as members two other Node objects, which each have as members two other Node objects, which each... well, you get the point).

You can, however, have a pointer to the class type as a member variable:

class Node {
    char *cargo;
    Node* left;   // I'm not a Node; I'm just a pointer to a Node
    Node* right;  // Same here
};

Solution 2 - C++

Just for completeness, note that a class can contain a static instance of itself:

class A
{
    static A a;
};

This is because static members are not actually stored in the class instances, so there is no recursion.

Solution 3 - C++

No, but it can have a reference or a pointer to itself:

class Node
{
    Node *pnode;
    Node &rnode;
};

Solution 4 - C++

Use a pointer, & better initialized:

class Node {
    char * cargo = nullptr;
    Node * left = nullptr;
    Node * right = nullptr;
};

Modern C++

It is a better practice to use smart-pointers (unique_ptr, shared_ptr, etc.), instead of memory allocations by 'new':

#include <string>
#include <memory> // For 'std::unique_ptr' 

class Node {
public:
    std::string cargo;
    std::unique_ptr<Node> left;
    std::unique_ptr<Node> right;
};

int main()
{
    auto bt = std::make_unique<Node>();

    (*bt).cargo = "Coffee";
    (*bt).left = std::make_unique<Node>();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeter StewartView Question on Stackoverflow
Solution 1 - C++James McNellisView Answer on Stackoverflow
Solution 2 - C++FelipeView Answer on Stackoverflow
Solution 3 - C++R Samuel KlatchkoView Answer on Stackoverflow
Solution 4 - C++Amit G.View Answer on Stackoverflow