0

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;

}
Naresh T
  • 309
  • 2
  • 14
  • the compiler adds the overload for you. It performs a shallow copy. If you are managing dynamic memory, you would not want to rely on the compiler. – Trevor Hickey Jan 18 '13 at 12:28

2 Answers2

2

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 accessible operator = 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.

Community
  • 1
  • 1
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

You can make use of a default implementation of the assignment operator if you do not use dynamic or other resources memory in your class. However if that is not the case and for instance you have a member that uses dynamically allocated memory this will be unsafe and may have unexpected effects.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176