Why does the below C++ program output "ACCA"? Why is operator int()
called twice?
#include "stdafx.h"
#include <iostream>
using namespace std;
class Base {
public:
Base(int m_var=1):i(m_var){
cout<<"A";
}
Base(Base& Base){
cout<<"B";
i=Base.i;
}
operator int() {
cout<<"C";
return i;
}
private:
int i;
};
int main()
{
Base obj;
obj = obj+obj;
return 0;
}
C does not support operator overloading at all. You can only implement operations as functions: Colour colour_add(Colour c1, Colour c2); Colour colour_substract(Colour c1, Colour c2); ... You could also switch to C++, but it may be overkill to do it just for the overloading.
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. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.
Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures. This feature is present in most of the Object Oriented Languages such as C++ and Java.
An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator. Overloaded operators are distinct from overloaded functions, but like overloaded functions, they are distinguished by the number and types of operands used with the operator.
First, this line:
Base obj;
Default-constructs object obj
by picking the constructor that accepts an integer, with default value 1
. This is responsible for the first A
being printed to the standard output.
Then, this expression:
obj + obj
Requires picking a viable overload of operator +
. In this case, since obj
has a user-defined conversion to int
, the built-in operator +
is picked, and both arguments are converted to int
. This is responsible for the two C
s being printed to the standard output.
Then, the assignment to obj
in:
obj = obj + obj
Needs to invoke the implicitly generated operator =
for Base
. The implicitly generated operator =
has signature:
Base& operator = (Base const&);
This means that the expression on the right side of the equal sign, which is of type int
, must be converted into a temporary Base
object from which obj
is assigned (the reference parameter of the implicitly-generated operator =
is bound to this temporary).
But the creation of this temporary from an int
in turn requires invoking the converting construction of Base
that accepts an int
again, which is responsible for the second A
being printed to the standard output.
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