user1448323
user1448323

Reputation: 159

C++ operator overloading - pointer, multiply

I wonder about the multiply operation(*) is overloading in pointer or vice versa?

Or the operators are individual?

C++

Upvotes: 3

Views: 3164

Answers (2)

James Kanze
James Kanze

Reputation: 153977

It works exactly like all of the operator symbols which can define a unary or a binary operator (+, - and & are the other ones), it depends on the number of arguments the function will take. Thus, a unary * should be defined to take a single operator, either as a non-static class member taking no arguments (other than this), or as a free function taking a single argument. The binary operator should be defined to take two arguments, either as a non-static class member taking one argument (in addition to this), or a free function taking two arguments.

Note that the names of the functions are considered the same, so a binary version can hide a unary one, or vice versa.

Upvotes: 5

Luchian Grigore
Luchian Grigore

Reputation: 258618

They are separate operators, and which one you overload depends on what parameters you pass to the operator.

struct A
{
    //dereference operator
    A /*or whatever*/ operator *() { /*...*/ };
    //multiply operator           
    A operator *(const A&) { /*...*/ };
};

//...
A a;
*a; //calls dereference operator
a * a; //calls multiply operator

Upvotes: 14

Related Questions