Question

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!!

Was it helpful?

Solution

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 :)

OTHER TIPS

The code will compile if the Functions are defined but not used. If they are defined and never used the optimiser will remove them. However if they are used then you will get a linker error.

It is bad practise to define a function and not fill it out. Especially if someone else is going to be using this code.

Although, chris makes a good point, in the comments. It may be useful if you don't want people using the default function. This is also why it lies in the private section, when something like copy or = should be publicly normally.

If you explicitly define a constructor you disable all other implicit constructors. So this has implications and can be useful in many situations. However I see no reason to define and leave empty the destructor (which is not even declared virtual).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top