I have the following class in a single .h file:
class MyClass
{
protected:
MyClass();
~MyClass();
private:
MyClass(const MyClass&);
MyClass& operator=(const MyClass&);
};
inline MyClass::MyClass()
{
}
inline MyClass::~MyClass()
{
}
What seems confusing to me is that there is no code where MyClass(const MyClass&) copy constructor and MyClass& operator=(const MyClass&) assignment operator overloading are implemented. The class just has the definitions but there is nothing else.
I've seen this in a code that I'm analyzing and it compiles perfectly. I'm new with C++ and in all the examples I've seen I found both the definition in the class and the implementation below or in a separate .cpp file
So, any one could explain why this code compiles and why would you include just the declaration of a function but not its implementation?
Thank you!!
Copy construction and assignment have been explicitly forbidden by the author.
If it is used externally, it will be an error (because it is private
). If it is referenced internally or by a friend
, then it will produce a link error because the definition does not exist.
In C++11, this is more clearly written as:
MyClass(const MyClass&) = delete;
MyClass& operator=(const MyClass&) = delete;
Here, the compiler will note this at compilation - no linker errors and clear intent without additional documentation :)