Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Default copy constructor

Tags:

c++

I understand compiler won't generate default copy ctor if copy ctor is declared private in a class.

But can someone explain why compiler does that?

What happens if copy ctor is declared protected? Would compiler provide default copy ctor?

What happens if copy ctor is declared private but have a definition e.g. foo(const& obj){}

like image 592
avinash Avatar asked Dec 21 '22 22:12

avinash


2 Answers

Any copy constructor declared in the class (be it private, public or protected) means the compiler will not generate a default copy ctor. Whether the one declared in the class is then also defined or not only controls whether code with the proper level of visibility into it can copy instances of the class (if not defined, the linker will complain; the compiler's job is only to complain about use without proper visibility, not to duplicate the linker's job).

For example, if you declare a private copy ctor, only code that is in functions in the class (or friends, of course) is allowed to compile if it tries copying an instance. If the ctor is not defined, that code, however, will not survive the linker, so you get an error anyway (just unfortunately a bit later in the build process, i.e. possibly with a modest waste of computational resources at build time compared with earlier-detected errors).

like image 124
Alex Martelli Avatar answered Jan 05 '23 23:01

Alex Martelli


The compiler knows a copy constructor exists, so it won't generate one. The accessibility (public / private / protected) or whether it has a definition aren't considered in this phase.

It sounds like there is no copy constructor just because you cannot call a private function from outside and non-friends. The user-defined constructor still exists, only that it is private.

If it's protected then only subclasses and itself can call the copy constructor. There will be no implicitly defined copy constructors either.

like image 42
kennytm Avatar answered Jan 06 '23 00:01

kennytm