tags:

views:

74

answers:

2

Hey, so if I have a Base class and 2 derived classes...

class Base
{
  virtual void Output()
  {
     cout << "OUTPUTTING A BASE OBJECT" << endl;
  }
};

class Derived : public Base
{
   void Ouput()
   {
     cout << "OUTPUTTING A DERIVED" << endl;
   }
};

class OtherDerived : public Base
{

};

As I understand it, if I try to call Output from OtherDerived, it would fail. Is there a way to override Output for some derived versions of Base but not others?

+9  A: 

Calling Output for objects of the OtherDerived class fails not because it's virtual, but because it's declared private in Base (well not explicitly - but private is the default in classes when nothing else is specified)

Change the declaration of Base to:

class Base
{
public:
  virtual void Output()
  {
     cout << "OUTPUTTING A BASE OBJECT" << endl;
  }
};

And this will work. protected will also work. Since Output isn't pure virtual, it can be called from subclasses that don't override it.

Eli Bendersky
Ah, didn't think of the default accessibility - good catch.
Evgeny
A: 

It would not fail - it would call Base::Output. What you want, ie. overriding "for some derived classes, but not others" is how inheritance works. You don't need to do anything further.

Evgeny