Am writing a program using copy constructor the code goes like this
class test
{
int a,b;
public:
test()
{
//statements
}
test(test &t) //copy constructor
{
a=t.a;
b=t.b;
cout<<a<<b;
}
};
void main()
{
test t;
test t1;
t1=t; //invoke copy constructor
}
it has to assign the vals of t obj to t1 but when am compiling it is not invoking the copy constructor can u people help me out.
Also, you don't even need to implement the copy constructor as newer compilers will autogenerate one for you that does a member-wise copy (older ones did a bit-wise copy which in your case would also work since your class contains only POD types [Plain-Old-Data]).
However, compilers do not autogenerate assignment operators, so you'd need to write
it:
1 2 3 4 5 6 7 8 9
class test {
// ... your stuff here
test& operator=( test const& rhs ) {
a = rhs.a;
b = rhs.b;
return *this;
}
};