Jan Rüegg
Jan Rüegg

Reputation: 10075

Disable copy/assignment, automatically disabled for children?

When using the following code to disable copy and assignment:

Foo(const Foo&) = delete;
Foo& operator=(const Foo&) = delete;

Will this also automatically disable copy and assigment of child classes of Foo?

class Bar : public Foo {
}

Or, in other words, can Bar be copied?

Upvotes: 3

Views: 794

Answers (2)

SACHIN GOYAL
SACHIN GOYAL

Reputation: 965

behavior of "delete" is similar to "boost::noncopyable" .In c++11 , compiler is doing the task for you .

// Example program
#include <iostream>
#include <string>

class Car {
public:
  Car(const Car&) = delete;
  void operator=(const Car&) = delete;
  Car(): owner(0) {}
  void setOwner() { owner = 0; }

private:
 int owner;
};
int main()
{
  Car c1,c3;
  Car c2=c1;//error
  c3=c1;//error 

}

Similarly ,when you will try to inherit this class , derived class will inherit the trait of being noncopyable as below

// Example program
#include <iostream>
#include <string>

class Car {
public:
  Car(const Car&) = delete;
  void operator=(const Car&) = delete;
  Car(): owner(0) {}
  void setOwner() { owner = 0; }

private:
 int owner;
};
class myCar:public Car{};
int main()
{
  myCar c1,c3;
  myCar c2=c1;//Error
  c3=c1;//Error

}

Below error :

 In function 'int main()':
19:12: error: use of deleted function 'myCar::myCar(const myCar&)'
15:7: note: 'myCar::myCar(const myCar&)' is implicitly deleted because the default definition would be ill-formed:
15:7: error: use of deleted function 'Car::Car(const Car&)'
7:3: note: declared here

Upvotes: 1

Mark B
Mark B

Reputation: 96281

Yes, this also inhibits implicit copying of child classes. In fact that's how inheriting from boost::noncopyable (http://www.boost.org/doc/libs/master/libs/core/doc/html/core/noncopyable.html) works. However someone could always write their own copy constructor/copy assignment for the child class that doesn't actually copy the Foo component, or copies it in a different way.

Upvotes: 3

Related Questions