C++ Compiler

3 views
Skip to first unread message

ravi ranjan

unread,
Aug 12, 2005, 5:12:29 AM8/12/05
to compg...@googlegroups.com
#include<iostream>
using namespace std;
class rational
{
public:
 rational(int m , int n = 1)  { x = m; y = n; cout<<"cons"<<endl;}
 rational(const rational & r)  { cout<<"copy"<<endl; }
 const rational operator +(const rational &r);
private:
 int x;
 int y;
 
};
const rational rational::operator +(const rational &r)
{
 return rational(x + r.x , y + r.y);
}
int main()
{
 rational r1(2,3);
 rational r2(4);
 rational r = r1 + r2;
 return 0;
}

The above code is compiled successfully using gcc compiler.
I am quite surprised to note that neither constructor or copy constructor is being called when executing statement  rational r = r1 + r2;
since here a temporary object is being create due to r1+r2 and  that temporary object is being assigned to r , so either construtor or copy constructor should be called by compiler.but its not calling.WHY?

-ravi


Check out Yahoo! India Rakhi Special for Rakhi shopping, contests and lots more.
http://in.promos.yahoo.com/rakhi/index.html

Dipendra Ganotra

unread,
Aug 14, 2005, 9:58:07 PM8/14/05
to compg...@googlegroups.com
Hi Ravi,
in your case it won't call any constructor not even copy. coz
copy constructor i guess is called when you are creating a object like
rational obj(r1 + r2) not while assignment. so in the code it will do
a memberwise assignment. if you want you can overload the assignment
operator.
i might be wrong if so please let me know the right reason.

Varghese Jacob

unread,
Aug 24, 2005, 12:04:02 PM8/24/05
to compg...@googlegroups.com
Hi Deepu,

The following is the output I got from the Ravi's program in msdev.
cons
cons
cons
copy
copy

As per my knowledge, copy constructors are called when an object is assigned to another object, at the time of its creation.
"rational r = r1 + r2;" is calling copy constuctor two times, as a temporary object will be created to store the return object of r1+r2. The returned object of r1+r2 is assiged to the temporary object, at the time of creation of the temporary object. The second time copy constructor will be called is when this temporary object is assigned to "r".

Correct me if I'm wrong.

Regards,
Varghese.

Rushabh Lathia

unread,
Aug 25, 2005, 2:07:22 AM8/25/05
to compg...@googlegroups.com
Hi Varghese,

You are right, but this output is when we run Ravi's program on msdev,
Ravi's question was using gcc compiler.

And with gcc compiler, output...
cons
cons
cons

So why it's like that in gcc compiler ???????

rgrds
Rushabh
Reply all
Reply to author
Forward
0 new messages