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?
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 (*).
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 .
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.
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.
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*();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With