Often times it\'s a good idea to have an abstract base class to isolate the inte
ID: 652464 • Letter: O
Question
Often times it's a good idea to have an abstract base class to isolate the interface of the object.
The problem is that copy construction, IMHO, is pretty much broken by default in C++, with copy constructors being generated by default.
So, what are the gotchas when you have an abstract base class and raw pointers in derived classes?
class IAbstract
{
~IAbstract() = 0;
}
class Derived : public IAbstract
{
char *theProblem;
...
}
IAbstract *a1 = new Derived();
IAbstract a2 = *a1;//???
And now do you cleanly disable copy construction for the whole hierarchy? Declare copy construction as private in IAbstract?
Are there any rules of three with abstract base classes?
Explanation / Answer
Copy construction on an abstract class should be made private in most cases, as well as assignment operator.
Abstract classes are, by definition, made to be a polymorphic type. So you don't know how many memory does your instance use, and so cannot copy or assign it safely. In practice, you risk slicing.
Polymorphic type, in C++, mustn't be manipulated by value. You manipulate them by reference or by pointer (or any smart pointer).
This is the reason why Java has made object manipulable by reference only, and why C# and D has the separation between classes and structs (the first one being polymorphic and reference type, the second one being non polymorphic and value type).
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.