I'm new to c++ can you explain pointers in this instance

Viewed 95

Why does line 18 Node* bob = new(); not give me an error while line 22 node actualValue = new Node; does.

#include <iostream>

using namespace std;

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

int main() {
    cout << "Hello, World!" << std::endl;
    int a = 200;
    int* ptr = &a;

    cout << a << " pointer is " << ptr << endl;

    Node* bob = new Node();
    bob->data = 1;


    Node actualValue = new Node;
    return 0;
}
4 Answers

Node* bob = new Node(); don't give error because new Node() returns a pointer Node* and the type of bob is also Node*. You can do assignments between pointers having same types.

Node actualValue = new Node; give error because the type of actualValue is Node and the class Node doesn't have any constructors that accept the pointer Node*.

In C++ when you declare a new instance of a class, you can skip the brackets if the constructor has no arguments.

However, this line

Node actualValue = new Node;

is incorrect as the actualValue variable is decalred in the stack, not in the heap. You can only use new operator with the pointer declarations.

You must come from another language or be a complete beginner, but that's not a problem. I'm here to help you.

In C++, you can create a stack, and a heap variable. The differences are here:

int stack_var = 5;
int* heap_var = new int;
*heap_var = 5;

The big difference is that a heap variable is allocated with the new keyword. You must also know, that stack variables are freed automatically, when the scope ends (basically when you reach the first '}' after the allocation). But you have to delete the heap variables like this:

delete heap_var;

This will free up the memory. The main problem you have is that calling new returns a pointer. A pointer is basically a memory address. A pointer is basically the declared the same as an object, but we add an asterix (*). Like this:

Someobject object;
Someobject* pointer;

So to wrap it up, you must modify the code like this:

Node* bob = new Node();
bob->data = 1;

Node actualValue;

//This is also important!!!
delete bob;

Or this:

Node* actualValue = new Node();

delete actualValue;

I didn't mention it, but it may not be trivial for a beginner: once you delete some memory, you can't access it anymore.

Another difference between stack and heap variables:

You access members of a stack object with a dot (.) operator (stack_obj.foo = 5), while in case of pointers, with the arrow (->) operator (pointer->foo = 5)

Hope it cleared it :D

Why does line 18 Node* bob = new(); not give me an error while line 22 node actualValue = new Node; does

The line in question is

Node actualValue = new Node;

new Node returns a pointer, you can't assign it to an instance of the Node class. And you forgot your parantheses after new Node to call the constructor. The correct code is

Node *actualValue = new Node();
Related