why sample as return type in operation overloading can anyone explain how this code works. why the return type is class itself whats the use of .x here
#include<iostream>
class sample
{
private:
int x;
public:
sample();
void display();
friend sample operator (sample ob3,sample ob4)
};
sample::sample()
{
x=1;
}
void sample::display()
{
cout<<x;
}
sample sample::operator (sample ob3,sample ob4)
{
sample ob5;
ob5.x=ob3.x ob4.x;
return(ob4);
}
int main()
{
sample ob1,ob2,ob3;
ob3=ob1 ob2;
ob3.display();
}
CodePudding user response:
why sample as return type in operation overloading
The return type is sample
because the author that wrote the operator overload chose to use sample
as the return type. It is quite typical for binary operator
overloads to have the same return type as the type of the operands.
Part of why it is typical is that it follows the example of all corresponding built-in operators which is a good convention to adhere to. When both operands of a built-in operator
have the same type (after conversion), the type of the expression is also the same. For example the operands of 1 1
are int
and the type of the expression is int
also. In cases where operands have different type (e.g. pointer arithmetic), the resulting type is one of the operand types.
whats the use of .x here
.
is an operator to access the member of an object. x
is a data member of and instance of the class sample
.