S
subramanian100in
Consider the following class( For simplicity I have not given the
member function definitions).
class Test
{
public:
explicit Test(int arg = -1);
Test(const Test& arg);
Test& operator=(const Test& rhs);
Test& operator+=(const Test& rhs);
int getValue(void) const;
private:
int value;
};
Suppose I define the overloaded operator+() as
inline const Test operator+(const Test& lhs, const Test& rhs)
{
Test temp = lhs;
temp += rhs;
return temp;
}
Consider the three instances of the class Test.
Test a(100);
Test b(200);
Test c(300);
I have kept the return type of operator+() as 'const Test' instead of
plain 'Test'. The reason is that if the return type were plain 'Test',
then it will allow the following expression:
(a + b) = c;
But we cannot write
(x + y) = z;
if x, y, z were built-in types. So, to mimic built-in types, the
overloaded operator+() has to return 'const Test' instead of plain
'Test' so that '(a+b) = c' will be disallowed by the compiler. Am I
correct ? Kindly advice me what is practiced regarding the return type
of operator+() in real-world applications?
Thanks
V.Subramanian
member function definitions).
class Test
{
public:
explicit Test(int arg = -1);
Test(const Test& arg);
Test& operator=(const Test& rhs);
Test& operator+=(const Test& rhs);
int getValue(void) const;
private:
int value;
};
Suppose I define the overloaded operator+() as
inline const Test operator+(const Test& lhs, const Test& rhs)
{
Test temp = lhs;
temp += rhs;
return temp;
}
Consider the three instances of the class Test.
Test a(100);
Test b(200);
Test c(300);
I have kept the return type of operator+() as 'const Test' instead of
plain 'Test'. The reason is that if the return type were plain 'Test',
then it will allow the following expression:
(a + b) = c;
But we cannot write
(x + y) = z;
if x, y, z were built-in types. So, to mimic built-in types, the
overloaded operator+() has to return 'const Test' instead of plain
'Test' so that '(a+b) = c' will be disallowed by the compiler. Am I
correct ? Kindly advice me what is practiced regarding the return type
of operator+() in real-world applications?
Thanks
V.Subramanian