Copy constructor with increment operator program

Hi,
I am doing some hands on and doing some program. I got the following input but not able to figure out the output. why am I getting this value.

This is default constructor
The pre-increment operator call
the vaue of pre increment is :1

if I provide the copy constructor(remove comment in below code) than got the following input.

This is default constructor
The pre-increment operator call
The constructor is :copy constructor
the vaue of pre increment is :0

I was expecting the same out as it has given above


#include<iostream>
using namespace std;

class sample
{
public:
sample& operator++();
sample operator++(int);
sample();
//sample(sample &s);
int i;
};

sample::sample()
{
cout<<"This is default constructor"<<endl;
i=0;
}
/*
sample::sample(sample &s)
{
cout<<"The constructor is :copy constructor"<<endl;
i=0;
} */
sample& sample::operator++()
{
cout<<"The pre-increment operator call"<<endl;
i++;
return *this;
}

sample sample::operator++(int)
{
cout<<" The pos- increment operator call"<<endl;

}


int main()
{
sample s;
sample d= ++s;
cout<<" the vaue of pre increment is :"<<d.i;
return 0;
}
1
2
3
4
5
sample::sample(sample &s)
{
       cout<<"The constructor is :copy constructor"<<endl;
       i=0;
}


Hmm, I wonder why i is 0 after you set it to 0?


remove that one also. but still i am getting the same result again.
In statement sample d= ++s; copy constructor is called. When you did not define your copy constructor sample(sample &s); ( when it was commented) the compiler created implicitly the following copy constructor sample( const sample &s);. The implicit copy constructor copies all members of one object of a class to another object. As in your example at first the pre-increment operator is called and after it the copy constructor is called then d.i is equal to 1.
When you uncomment your copy constructor it is used instead of the implicit copy constructor. Your copy constructor sets i equal to 0. So you get that d.i is equal to 0.

Also you can get in the second case that d.i will be equal to 1 due to allowed by the Standard optimization. That is the compiler is allowed do not use copy constructor to copy innamed temporary objact and to build it directly in object d.
Last edited on
Topic archived. No new replies allowed.