Protected constructor to make the base class incompatible

Is it good practice to protect the constructor of the base class if I want to avoid instances of it? I know that I could also have a clean virtual dummy, but that seems weird ...

Pay attention to the following code:

#include <iostream>

using std::cout;
using std::endl;

class A 
{
protected:
    A(){};
public:
    virtual void foo(){cout << "A\n";};
};

class B : public A
{
public:
    void foo(){cout << "B\n";}
};

int main()
{
    B b;
    b.foo();
    A *pa = new B;
    pa->foo();

    // this does (and should) not compile:
    //A a;
    //a.foo();
    return 0;
}

Is there a flaw or side effect that I do not see?

+4
source share
4 answers

It is customary to defend base class constructors. When you have a purely virtual function in your base class, this is not required, since you cannot create it.

, .

. , .

+4

, , , , , , . / ,

  • , . .
  • , , . , , .
  • , , . , .

, , .

+2

, .

, . -

struct B : A {
   // Just to workaround limitation imposed by A author
};

, ... , , .

.

+1

. , , .

, .

class AbstractBase
{
public:
    virtual ~AbstractBase() = 0;
};
inline AbstractBase::~AbstractBase() {}

, inline.

0

All Articles