Hi Everyone,
It seems that pure virtual member functions can be defined in the
abstract base class, but what is the need (or) use to do so? and how
is it done?
Thanks in advance!!!
Why not define a pure-virtual member function if thats what the
hierarchy requires?
C++ does not impose the rule that an abstract class is an 'interface'
with no implementation. Neither does the language prevent you from
indeed choosing that route.
You can implement that member function where its needed in those
special cases where providing a definition in the abstract base fits
the requirement.
#include <iostream>
class abstract
{
public:
virtual void foo() = 0;
};
void abstract::foo()
{
std::cout << "abstract::foo()\n";
}
class concrete : public abstract
{
public:
void foo()
{
abstract::foo();
std::cout << "concrete::foo()\n";
}
};
int main()
{
concrete instance;
instance.foo();
}
/*
abstract::foo()
concrete::foo()
*/
Now consider what would happen if you needed to design a class
'derived' that also inherits from abstract (assume that deriving from
concrete would not fit the requirements for whatever reason). Consider
what would happen if
std::cout << "abstract::foo()\n";
where say... 60 lines of code that you need to maintain. All of a
sudden, its far from being silly.