I am implementing a new feature.
I have a simple class with boolean variables.
I didn’t implement operator= function in it.
Still, When I copy objects using operator = the values are being copied.
Can you please explain how it is working?
How safe is it not to write this function, where as, in my application, many times, I’ll be copying these objects using operator ‘=’
#include <iostream>
using namespace std;
class A
{
public:
bool abc;
bool xyz;
};
int main()
{
A obj1, obj2;
obj1.abc = true;
obj1.xyz = false;
obj2 = obj1;
cout<<"obj2 abc: "<<obj2.abc<<endl; //How do the values got copied?
cout<<"obj2 xyz: "<<obj2.xyz<<endl;
}
It’s safe if your class isn’t managing resources. The default
operator =does a member-wise copy. This is a shallow copy, so all members that have an accessibleoperator =available will be correctly copied.The default is not safe if the class is managing resources (dynamic memory, streams, handles, etc.) – see the rule of three.