yabhishek
yabhishek

Reputation: 419

Allocating memory to this object in c++

I have a class called Node which has two constructors. When I try to call one of the constructors from the other and assign it to the memory pointed by this of the caller I don't get any error. But when I try to assign memory/object allocated on heap using new to this I get an error expression is not assignable. Following is my code. What could be the possible reasons?

class Node{
    private:
       int key;
       Node* left, *right;
    public:
       Node(){
           left=NULL;
           right= NULL;
       }

       Node(int data){
           this=new Node(); // generates error 'expression is not assignable'
           *this= Node();   //compiles succesfully
           this->key=data;   
       }
}

Upvotes: 0

Views: 51

Answers (1)

cdhowie
cdhowie

Reputation: 169123

C++11 allows delegating constructors:

class Node {
    private:
       int key;
       Node* left, right;

    public:
       Node() {
           left = NULL;
           right = NULL;
       }

       Node(int data) : Node() {
           this->key=data;   
       }
};

A few other comments about your code:


Node* left, right;

This declares left to be pointer-to-Node and right to be Node (not a pointer), as though you had written this:

Node* left;
Node right;

This is why you place the asterisk to the left of the variable, not the right of the type:

Node *left, *right;

Or, even better:

Node *left;
Node *right;

left = NULL;

In C++11, use nullptr instead of NULL. You should be using an initializer list anyway:

Node() : left(nullptr), right(nullptr) { }

Upvotes: 4

Related Questions