Reputation: 60341
How to call an overloaded operator in another member function of a class in C++ ?
Upvotes: 0
Views: 114
Reputation: 739
The overloaded operator will be called automatically and there is no need for explicit calling. Here is a quick example of operator overloading:
class MyNumber
{
private:
int number_;
public:
MyNumber() : number_(0) { }
MyNumber& operator++() // prefix
{
++number_;
return *this;
}
MyNumber operator++(int) // postfix
{
MyNumber result = *this;
++number_; // Calls this->operator++(void);
return result;
}
};
int main(void)
{
MyNumber number;
number++;
++number;
return 0;
}
Upvotes: 0
Reputation: 20997
Your question is quite ambiguous but one of those three subanswers should work:
Whenever you want use this
inside any (non-static) member function you can do it:
class A {
int b;
void foo() {
this->b;
}
void bar() {
foo(); // Those calls are the same
this->foo();
this->b;
}
}
C++ takes care about this
being the same object.
When you want to call overloaded operator like operator+=
, you may do:
void foo()
{
*this += bar;
(*this)[bar]; // for operator[]
}
And if you need to call operator of parent class:
class A, public Base {
void foo()
{
this->Base::operator+= bar; // Equivalent syntax again
((Base)*this) += bar;
}
}
Upvotes: 1
Reputation: 490048
Assuming it's overloaded as a member, you generally use (*this)operator<parameter(s)>
, so if a class has an overload of operator[]
that takes, say, an int parameter (e.g., T &operator[](int index);
), another member function can invoke it with (*this)[2]
.
If it's overloaded as a free function, you do pretty much the same sort of thing. For example, assuming you had a free function like:
my_string operator+(my_string const &a, my_string const &b);
You could invoke it from a member function like:
my_string operator+(my_string const &other) {
return (*this) + other;
}
Probably not useful in quite this simplistic of a case, but still shows the general idea.
Upvotes: 6