Search code examples
c++objectpointerslinked-listdereference

How to dereference pointer object in C++?


I am getting error while running this? cout << *head << endl; Why we cant dereference Object pointer? Like wise we do in int data type:

int obj = 10;
int *ptr = &obj;
cout << *ptr << endl; //This will print the value 10 by dereferencing the operator!

But not in object why?

#include <iostream>
using namespace std;


class Node
{
    public:
    int data;
    Node *next;
    Node(int data)
    {
        this->data = data;
        this->next = NULL;
    }
};

int main() {
    Node N1(10);
    Node *head = &N1;
   
    cout << &N1 << endl;
    cout << head << endl;
    cout << *head << endl;
    cout << &head << endl;
}

Solution

  • The fact that you're dereferencing a pointer is a red herring: std::cout << N1 << endl; will not compile for the same reason.

    You need to implement std::ostream& operator<<(std::ostream& os, const Node& node) for (at global scope) your Node class, which in the function body you'd write something along the lines of

    {
        os << node.data; // print the data
        return os; // to enable you to 'chain' multiple `<<` in a single cout statement
    }