views:

151

answers:

5

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 BaseClass
{
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;
A: 

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
}
Jdubs
#1 that won't solve the issue at hand, and #2 it's not valid C++. (Control reaches the end of a non-void function)
Billy ONeal
+10  A: 

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.

sharptooth
In this case, the copy-assignment operator, surely?
Charles Bailey
@Charles Bailey: Yeap, edited. Thanks for the notice.
sharptooth
You can as well make the Constructor `protected`.
Matthieu M.
Thanks for your solution, sharptooth, this indeed prevents this type of cast and further reassigning.
Some One
+2  A: 

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.

Billy ONeal
+1  A: 

You can prevent *base_1 = *base_2 by making BaseClass's assignment operator protected, but you can't prevent base_1 = base_2.

Ken Bloom
A: 

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.

baris_a