C++ Virtual Functions Question
Hey, so if I have a Base class and 2 derived classes...
class Base
{
vi开发者_运维技巧rtual 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?
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.
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.
精彩评论