"member of type foo has private copy constructor" error: why's it an error?

c++, class, copy-constructor

Solution

In the first version, when you are copying instances of `my_class`, and you must be somewhere that you're not showing us, you are doing a deep copy of `someone_elses`.

In the latter version, when you do the same thing, you are making a shallow copy of a pointer to an instance of `someone_elses`. Thus you don't make a copy but instead have a pointer to the same instance in both copies of `my_class`.

Since you are in fact deleting `someone_elses` in your destructor you are going to run into all kinds of problems. You need to be able to copy `someone_elses` but it seems you're not allowed to for some reason that the author of that class thought was so important that they made it impossible.

How to respond to this problem depends too much on the details you left out. It may be that you cannot allow copies of `my_class` and should be making its copy constructor private as well. This will of course break something somewhere else because that constructor is not created if it's not used.

Problem

I was trying to define a class like this: ``` #include <library/foo.h> class my_class { private: someone_elses foo; public: myclass(); ~myclass(); //... }; ``` But the compiler failed: "field foo of type someone_elses has a private copy constructor". Now I know that I can address this by: ``` class my_class { private: someone_elses *foo; //... }; my_class::my_class() { foo = new someone_elses(); } my_class::~my_class() { delete foo; } ``` My question is why does the compiler care whether an object's field implements an accessible copy constructor?

Original source

Related problems