C++ Class Inheritance architecture - preventing casting
I have a structure of base class and a couple of inherited classed. Base class should be pure virtual class, it should prevent instantiation. Inherited classes can be instantiated. Code example below:
class Bas开发者_开发百科eClass
{
public:
BaseClass(void);
virtual ~BaseClass(void) = 0;
};
class InheritedClass : public BaseClass
{
public:
InheritedClass1(void);
~InheritedClass1(void);
};
class DifferentInheritedClass : public BaseClass
{
public:
DifferentInheritedClass(void);
~DifferentInheritedClass(void);
};
I want to prevent the following operations to happen:
InheritedClass *inherited1 = new InheritedClass();
DifferentInheritedClass *inherited2 = new DifferentInheritedClass ();
BaseClass *base_1 = inherited1;
BaseClass *base_2 = inherited2;
*base_1 = *base_2;
Make the copy constructor and the assignment operator in BaseClass
protected. The class is non-creatable already, so you don't need public copy-constructor and assignment operators. With protected copy constructor and assignments operators you can call it from the derived classes constructors and assignment operators.
You can't prevent other programmers from using a cast. They are free to interpret your memory layout however they wish with reinterpret_cast
or a C-style cast, though doing so invokes undefined behavior.
EDIT: As sharptooth said, you can make baseclass' copy constructor protected to prevent some of these kinds of problems though.
You can prevent *base_1 = *base_2
by making BaseClass's assignment operator protected, but you can't prevent base_1 = base_2
.
If it is OK for you to use Boost C++ Libs, then you can use boost::non_copyable base class. Or as written above you can declare required operations as protected, like copy constructor or assignment operator.
It's been quite sometime since I've programmed in C++, but is it possible for you to overload an operator for BaseClass to prevent the assignment from happening?
Maybe something along the lines of:
BaseClass& BaseClass::operator=(const BaseClass& myVar)
{
if(this != &myVar)
return *this
}
精彩评论