Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an instance of a class in the class itself [duplicate]

I am new to C++ and have a question:

Compare following code:

class Node { 
public:
    int data;
    Node* x;
};

and

class Node { 
public:
    int data;
    Node x;
};

I know the second part of code can't pass compile. But I want to know the reason.

Is it related to memory allocation or just syntax regulation?

I would be appreciate if someone can solve my question.

like image 522
Oh2 Avatar asked Oct 23 '14 12:10

Oh2


People also ask

Can you create an instance of a class inside a class?

In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and creates more readable and maintainable code.

How do you create an instance of a class?

Instantiating a ClassThe new operator also invokes the object constructor. Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

Can a class create an instance of itself C++?

A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type.

How do you duplicate a class instance in Python?

Use the deepcopy function to create an identical instance with a new pointer (as opposed to a shallow copy, which is another variable pointing to the same object).


1 Answers

If you could, then a Node would contain a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node, which contains a Node... and so on until the universe is full of Nodes and implodes.

like image 74
molbdnilo Avatar answered Sep 20 '22 15:09

molbdnilo