Roey Mizrahi
Roey Mizrahi

Reputation: 31

Create an abstract class without an abstract method

I have 3 classes, A, B, and C:

class A
{
/// Some Code
};

class B : public A
{
/// Some Code
};

class c : public B
{
/// Some Code
};

I want to make class A and B abstract classes in order to prevent creating instances of them, but neither of these two classes have an abstract method. Is there a way to make a class abstract even if it has no abstract methods?

Upvotes: 2

Views: 350

Answers (1)

Cody Gray
Cody Gray

Reputation: 244782

Odds are, if you're using the classes as base classes as shown in the sample code, they should have virtual destructors. And because a destructor is a method, you can make this a pure virtual ("abstract") destructor to make the class itself "abstract".

Note that an implementation can still be provided for a pure virtual method, so you can use the following code:

class A
{
  public:
    virtual ~A() = 0; 

/// Some Code
};

class B : public A
{
  public:
    virtual ~B() = 0;

/// Some Code
};

class C : public B
{
  public:
    virtual ~C() = 0;

/// Some Code
};
A::~A()  { }
B::~B()  { }
C::~C()  { }

Because base class destructors are always called when destroying an object, you need not call the base class implementation explicitly in the destructors for derived classes.

This should give you the desired effect. However, I'm currently struggling to come up with a compelling application for this design. The whole purpose of an abstract class in C++ is to define an interface, and you cannot have an interface unless there are methods defined that compose that interface. Either I am just not sufficiently clever, or you should possibly rethink your design.

Upvotes: 2

Related Questions