Monday 15 June 2015

c++ - How does defining prototypes for copy constructor in private section of class prevents copying of class? -



c++ - How does defining prototypes for copy constructor in private section of class prevents copying of class? -

how defining prototypes re-create constructor in private section of class prevents copying of class in c++

in c++, fellow member functions in private section of class can called other fellow member functions of same class. (similarly, protected members can called derived classes, , public members can called anyone.)

in order re-create object, need re-create constructor. if don't write own, compiler supply 1 you. if do write own, usual access rules apply. if set definition of re-create constructor in private section of class, compiler see there constructor right signature (so won't provide one), complain can't phone call because it's private.

back in old c++98 days, usual way prevent copying of class. c++11 has improve approach: say

struct mytype { mytype(const mytype&) = delete; };

to explicitly compiler "i not providing function, , not generate function me". has same effect defining private re-create constructor, provides improve error message attempting re-create class.

c++ copy-constructor

No comments:

Post a Comment