5

I want to make an abstract class in c++ with a single, but with some default implementation. so that every class that inherits it will have default behavior but you cant create an instance of the base class. but if i mark foo as pure virtual, I can't add an implementation to it.

class Base
{
public:
    virtual void foo() =0; //Now I can't add foo implementation
};

My solution was to not have it as a pure virtual, and just hide the constructor. I'm wondering if its possible to mark the class as pure, but still have some implementation?

Bg1987
  • 1,129
  • 1
  • 11
  • 25
  • 4
    What, exactly, is wrong with "my solution was to not have it as a pure virtual, and just hide the constructor"? That sounds perfectly reasonable. – James McNellis Jan 10 '12 at 07:54
  • 1
    There's no problem with providing an implementation for a pure virtual function. But I agree with James, your original idea is probably best. – Cody Gray - on strike Jan 10 '12 at 07:55
  • Using a private constructor is probably the way to go. Or if you have a C++11 compiler you can mark the constructor as [deleted](http://en.wikipedia.org/wiki/C++11#Explicitly_defaulted_and_deleted_special_member_functions). – Some programmer dude Jan 10 '12 at 07:55
  • @JoachimPileborg: You'll need to make it protected (and not deleted) to be able to instantiate derived classes. – Mike Seymour Jan 10 '12 at 08:12

1 Answers1

10

You can add an implementation to a pure virtual function. Classes that derive can use the default implementation by explicitly invoking the base-class-method.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283