pointers to classes

what does "this" keyword means and also the line Node* headnode = new Node() mean.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Node
{

public:

void set(int object){
this->object=object;
}


private:
int data;
Node * headnode;

};




 Node * headnode = new Node();
Last edited on
this is a pointer. In every instance of a class, it points to that instance of the class; points to itself.

Node* headnode
This means "create a new Node pointer, named headnode"

new Node();
This means "create a new Node object, on the memory heap, and give me a pointer to it".

= means assign the value of the thing on the right to the thing on the left

Node * headnode = new Node();
So this creates a new Node object on the heap, and headnode is a pointer to that new Node object.


The new Node() is value initialization:
http://en.cppreference.com/w/cpp/language/value_initialization
A new Node would be default initialization:
http://en.cppreference.com/w/cpp/language/default_initialization

The Node* headnode = expression; is copy initialization:
http://en.cppreference.com/w/cpp/language/copy_initialization


A member function
1
2
3
void Node::set( int object ) {
  this->object = object;
}

that is called, for example:
1
2
3
4
Node foo;
foo.set( 42 );
Node* bar = &foo;
bar->set( 7 );


Is like a standalone (friend of Node) function (in imaginary world where classes have no member functions):
1
2
3
void set( Node* this, int object ) {
  this->object = object;
}

that has to be called:
1
2
3
4
Node foo;
set( &foo, 42 );
Node* bar = &foo;
set( bar, 7 );


In member function the this is automatically defined. Implicitly.



PS. Your class Node does not have member 'object'. It does have member 'data' ...
Last edited on
Sir i have another question when an object is initialized than if we do not delete its address by using delete operator and make a new object by writing function than this object exists in heap memory or it is overrides and a new object takes place.
If you create an object using new, and you never delete that object, it will still exist.
Topic archived. No new replies allowed.