0

I want to create an abstract class with a pure virtual private method but I can't implement that in my concrete class. My option is to make that pure virtual private method to protected but in my concrete class I want to make it only a private. Like,

class IFoo
{
public:
    IFoo(){}
    virtual ~IFoo(){}

protected:
    virtual void fooMethod() = 0;
};

class Foo : public IFoo
{
public:
    Foo(){}
    virtual ~Foo(){}

private:
    virtual void fooMethod() {}
};

Is there any implication doing this? Or this is just fine?

Thanks!

domlao
  • 15,663
  • 34
  • 95
  • 134
  • 1
    Overriding private virtual functions is allowed and valid. Please see [this](http://stackoverflow.com/q/3970279/183120). – legends2k Oct 20 '13 at 07:13
  • @HansPassant how? IFoo's method is protected and thus wouldn't be callable for clients. – legends2k Oct 20 '13 at 07:23
  • @HansPassant: No! since it's _pure_ virtual it can't be called – legends2k Oct 20 '13 at 07:33
  • @HansPassant: [Wrong again](http://coliru.stacked-crooked.com/a/a2ac88a61362373e) :) Casting to this to `IFoo*` and calling gives _error: `virtual void IFoo::fooMethod()` is protected_. I also tried `IFoo::fooMethod` inside `Foo`'s method which gives a linker error. – legends2k Oct 20 '13 at 07:53
  • @legends2k - pure virtual functions can be called if you provide an implementation for them. The only real requirement is that subclasses implement them. For instance, if you want to ensure that a base class is never instantiated, you could give it a pure virtual destructor. Even if you have an implementation for the destuctor, it's still an abstract class. In fact, the destructor must have an implementation, but it may be the only function in the base class that you want to keep abstract. – Charlie Oct 21 '13 at 02:45
  • @Charlie: of course, I think you got mistook the point I was making. But the point I was making to Hans was that _in this particular situation_ one cannot call `IFoo::fooMethod` either from a child or from outside since it's protected. It can only be overridden. The comment above which says _No! since it's pure virtual it can't be called_ was poor choice of words! I meant in this case since there's no implementation given by the base, it cannot be called. From compiler's viewpoint it can, but the linker would bark for an undefined reference. – legends2k Oct 21 '13 at 04:17

1 Answers1

2

Why can't you make the method private in the base class? Making them private is a pretty standard design pattern for C++. Then the base class implements public/protected methods that call the private ones.

http://www.gotw.ca/publications/mill18.htm has way more info on the uses of public/private/protected virtual methods.

Charlie
  • 1,487
  • 10
  • 9