Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 995
Peter Stewart Avatar asked Apr 24 '10 21:04

Peter Stewart


People also ask

Can a class have a member of its own type C++?

No, you can't do that. Cell is an incomplete type until the closing brace of the class definition. You can't instantiate a standard container over an incomplete type.

What is class member in C?

Class members are initialized in constructors which can be overloaded with different signatures. For classes that do not have constructor, a default constructor that initializes the class members (to default values) will be generated. Unlike in C++, C# allows a class to inherit from one base class only.

Can classes have member functions?

In addition to holding data, classes (and structs) can also contain functions! Functions defined inside of a class are called member functions (or sometimes methods). Member functions can be defined inside or outside of the class definition.

Can a class have no members?

It is just called "stateless". Nothing really special about it. Show activity on this post. There is nothing wrong with a class that has no members; controllers do this very frequently.


1 Answers

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 }; 
like image 147
James McNellis Avatar answered Sep 29 '22 16:09

James McNellis