class A
{
int num;
public:
A() {}
A(int _num) : num(_num) {}
A operator + (const A & ob)
{
return (num+ ob.num);
}
};
int main()
{
A ob1(1);
A ob2(2);
A ob3(3);
A ob4=ob1+ob2+ob3;
}
My doubt is in ob1+ob2+ob3 . First ob1+ob2 is evaluated and a temporary object is created . The temporary is of const type . Next the operator function of the const object is created . So we have to explicitly state that the function is const otherwise it should result in compilation error right . But the above code executes without any error . Plz enlighten me
abhi74k
0
Newbie Poster
Recommended Answers
Jump to PostWhy would the temporary be
const
?
Jump to PostAddition is left to right in c++. So ob2 and ob3 are added together to form a const A. Then ob1 and that const A returned from the previous addition are added together.
ob4 = ob1.operator+( ob2.operator+(ob3) );
Hope this will clear that up for you.
Jump to PostNo you are confusing yourself. This is what happens as pointed out :
A ob4 = (ob1.operaotr+(ob2)).operator+(ob3);
But I think your problem is that this code :
A operator + (const A & ob){ return (num+ ob.num); }
This code does NOT return a …
All 11 Replies
Ariste
0
Newbie Poster
abhi74k
0
Newbie Poster
NathanOliver
429
Veteran Poster
Featured Poster
mrnutty
761
Senior Poster
abhi74k
0
Newbie Poster
Aranarth
126
Posting Whiz in Training
Fbody
682
Posting Maven
Featured Poster
abhi74k
0
Newbie Poster
mrnutty
761
Senior Poster
NathanOliver
429
Veteran Poster
Featured Poster
Aranarth
126
Posting Whiz in Training
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.