Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload dereference operator

I'm trying to overload the dereference operator, but compiling the following code results in the error 'initializing' : cannot convert from 'X' to 'int':

struct X {
    void f() {}
    int operator*() const { return 5; }
};

int main()
{
    X* x = new X;
    int t = *x;
    delete x;
    return -898;
}

What am I doing wrong?

like image 890
big-z Avatar asked Mar 24 '10 07:03

big-z


People also ask

What does the dereference operator (*) do?

In computer programming, a dereference operator, also known as an indirection operator, operates on a pointer variable. It returns the location value, or l-value in memory pointed to by the variable's value. In the C programming language, the deference operator is denoted with an asterisk (*).

What is dereference operator in C++?

The . * operator is used to dereference pointers to class members. The first operand must be of class type. If the type of the first operand is class type T , or is a class that has been derived from class type T , the second operand must be a pointer to a member of a class type T .

What are operator overloading in C++?

Operator Overloading in C++ In C++, we can make operators work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.

What is the difference between dereference operator and reference operator?

I read about * referencing operator and & dereferencing operator; or that referencing means making a pointer point to a variable and dereferencing is accessing the value of the variable that the pointer points to.


1 Answers

You should apply dereference operator to a class type. In your code x has a pointer type. Write the following:

int t = **x;

or

int t = x->operator*();
like image 126
Kirill V. Lyadvinsky Avatar answered Sep 30 '22 14:09

Kirill V. Lyadvinsky