Wednesday, August 19, 2009

c++: operator+(int m) const: a=b+c+5

class X {
public:
X&operator=(const X& rhs);
const X& operator+(const X& rhs) const;
const X& operator+(int m);
private:
int n;
};

int main()
{
X a,b,c;
//Statement goes here
return 0;
}

Given the sample code above, which one of the following statements is illegal?

a=b+5;
a=a+5+c;
(c=a+a)=b+c;
a=b+c+5;
a=a=b+c

a=b+5; -- non const object b invoking "+" with integer 5 - okay for const X& operator+(int m);!!
a=a+5+c; -- a+5 creates a const temporary of type X which is added to C . So a const temporary object of X invoking
const "+" with non const C - okay for const X& operator+(const X& rhs) const
(c=a+a)=b+c; -- causes addition of a+a ; and assignment of b+c to c - okay individually for const X& operator+(const X& rhs) const
a=b+c+5; -- b+c creates a temporary constant object of X which calls non constant operator function for "+" owing to the integer parameter 5 .This is not allowed as it would leave the "+" capable of modifying the constant..SO ILLEGAL
a=a=b+c -- assignment of a and addition of b+c - okay !!

No comments:

Post a Comment