-
December 10th, 2009, 01:25 PM
#1
prevent copying
in C++, to prevent copying, we can declare the copy constructor private in the class. It is recommended to have the copy constructor in the parent class if possible to prevent copying so that we can get a compile time error if child class copying is attempted. My question is why is this needed. If we just declare the copy constructor private in child class, we should get a compile time error isn't it?
Any ideas?
thanks,
Sam
-
December 10th, 2009, 01:32 PM
#2
Re: prevent copying
Originally Posted by samitj
in C++, to prevent copying, we can declare the copy constructor private in the class.
Both the copy constructor and copy assignment operator should be declared private.
Originally Posted by samitj
It is recommended to have the copy constructor in the parent class if possible to prevent copying so that we can get a compile time error if child class copying is attempted. My question is why is this needed. If we just declare the copy constructor private in child class, we should get a compile time error isn't it?
I think that the context is where the parent class is an abstract base class, thus it cannot be copied to begin with, but it also makes sense to disable copying for all child classes. Thus, to enforce the disabling of copying for all child classes, copying for the parent class is disabled even though no objects of the parent class' actual type can exist.
-
December 10th, 2009, 01:41 PM
#3
Re: prevent copying
Originally Posted by laserlight
Both the copy constructor and copy assignment operator should be declared private.
I think that the context is where the parent class is an abstract base class, thus it cannot be copied to begin with, but it also makes sense to disable copying for all child classes. Thus, to enforce the disabling of copying for all child classes, copying for the parent class is disabled even though no objects of the parent class' actual type can exist.
Right, but in both cases, either declaring them private in child or parent class, we will get a compile time error. So that argument is not correct.
-
December 10th, 2009, 01:44 PM
#4
Re: prevent copying
Originally Posted by samitj
Right, but in both cases, either declaring them private in child or parent class, we will get a compile time error. So that argument is not correct.
You're missing the point: suppose that copying is not disabled for the parent class. Suppose that for a child class copying is not disabled by mistake. Now, you will not get a compile error, but may possibly be open to a logic error if somewhere copying of an object of the given child class is performed by mistake. So, this is about defensive programming.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|