#include<iostream>
usingnamespace std;
class counter
{
int val;
public:
~counter()
{
cout<<"destructor"<<endl;
}
counter(counter&)
{
cout<<"copy constructor called"<<endl;
}
counter():val(0)
{}
counter& operator++()
{
++val;
*this;
}
int getval()
{
return val;
}
};
int main()
{
counter i;
cout<<"the value is"<<i.getval()<<endl;
++i;
cout<<"the value is"<<i.getval()<<endl;
counter a=++i;
cout<<"the value is"<<i.getval()<<endl;
cout<<"the value is"<<a.getval()<<endl;
}
i am getting the wrong output:
the value is 0
the value is 1
copy constructor called
the value is 2
the value is 1628937800
destructor
destructor
if i comment the copy constructor i am getting the correct output:
the value is 0
the value is 1
copy constructor called
the value is 2
the value is 2
destructor
destructor
if you want to write your own copy constructor
you have the responsibilities to copy all of the data you need
the nasty part of the self define copy constructor is--they wouldn't told you you didn't copy all
of the data you have to copy
usually we don't need to mess-up with self defined copy constructor if we
didn't do any dynamic memory allocation
but it is a good practice to play with self defined copy constructor since the
containers of the standard may not satisfied some special applications
But most of the time stl is good enough to handle those applications
I do hope someday I could create those containers and algorithms like stl did