Operator overload

S

semut

Hi, just like to find out when will this operator overload function
gets triggered?


Code Snippet

class A {


public:
enum enA {
A1, A2, A3
} value;

A();
virtual ~A();
A::enA& operator=(const UIScsiimInitReasonCode::enA& );
operator A::enA() {
return(value);
};


friend ostream& operator<< ( ostream&, const A&);
};

I know of the when will operator << and operator = be called, but I am
not sure when will the
operator A::enA() be called and what is the use (beside calling the
operator function directly like
a->operator A::enA()) ?

thanks
 
O

Ondra Holub

It is typecast operator. So it is called when instance of A is
typecasted to A::enA (either implictly or explicitly).

Look on following code:

#include <iostream>

class A
{
public:
enum enA { A1, A2, A3 };

A() { }
~A() { }

operator A::enA() { return A2; }
};

void Fn(A::enA e)
{
std::cout << "Fn(A::enA)\n";
}

void Fn(...)
{
std::cout << "Fn(...)\n";
}

int main()
{
A a;
Fn(a); // Will call Fn(A::enA) due to overload of operator A::enA()
return 0;
}

There are 2 overloaded functions Fn. You can guess, which one is
called, when parameter is instance of A.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top