I have made the following Car class:
class Car
{
private:
int id;
int* data;
public:
Car(int id, int data) : id(id) , data(new int(data)){}
//Car(const Car& rhs) : id(rhs.id) , data(new int(*rhs.data)){}
void print(){std::cout << id << " - " << *data << " - " << data << std::endl;}
};
With the following main code:
int main()
{
Car A(1,200);
A.print();
Car B=A;
B.print();
}
When I run this code I get the following output:
1 - 200 - 0x14bdc20
1 - 200 - 0x14bdc20
This is also what I expected as the default assignment operator simply copies the values of id and data.
When I comment in the copy constructor and run the same code, I get the following output:
1 - 200 - 0x71bc20
1 - 200 - 0x71c050
Hence, the data pointer of B points to a new address. I do not quite understand why this happens. I thought the default assignment operator still would only copy the values from A and the only way to solve this was to overload the assignment operator. How is it the default assignment operator seems to use the copy constructor in this case?