Morgan
Morgan

Reputation: 1897

C++ Virtual Functions Question

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?

Upvotes: 0

Views: 279

Answers (2)

EMP
EMP

Reputation: 61971

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.

Upvotes: 0

Eli Bendersky
Eli Bendersky

Reputation: 273366

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.

Upvotes: 10

Related Questions