I declare a class’s copy-ctor and operator= private to make its objects un-copyable, and don’t provide definitions for them both. So if the class’s friends invokes copying behavior on these objects, a link-time error would occur, right?
class A
{
public:
...
private:
A(const &a);
A& operator=(const &a); //just declarations, no definitions
};
But in order to move the error from link-time to compile-time, I learned from a book that I can do this:
class UnCopyable
{
public:
...
private:
Uncopyable(const &u);
Uncopyable& operator=(const &u); //also no definitions
};
then make A inherit Uncopyable,
class A: private Uncopyable
{
...
};
And it says in the book, if someone invokes copying on A, then A should call Uncopyable‘s copying counterparts first, but Uncopyable‘s copy-ctor and operator= are private, so this will fail and error will rise, which occur in compile-time.
My question is why would that occur in compile-time?
Because violations of the semantics of the language are compile-time errors, whereas link-time errors are errors that result from a function being declared but the linker cannot find a definition for it.
In other words, a linker error means your program is a valid C++ program and has gotten to the linking stage where the linker is just patching up references to functions in other compilation units (since the compiler only considers one compilation unit at a time) but it has searched everywhere and can’t find a definition. A compile-time error means your program violates the rules of C++ somehow.
However, you’re a little incorrect in your assumption. Making the
operator=privatewill cause a compile time error for people who try to assign those objects. The only time you’ll get a linker error is when a function that has access to that class’s private functions (e.g. afriendfunction or member function) then you’ll get a linker error.