pure virtual member functions

R

Rahul

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!!!
 
A

Alf P. Steinbach

* Rahul:
Hi Everyone,

It seems that pure virtual member functions can be defined in the
abstract base class,

They can, yes.

but what is the need (or) use to do so?

For a pure virtual destructor you need to provide an implementation if
there will ever exist an instance of a derived class.

and how is it done?

The implementation must be defined outside the class.

Hth., even if it sounds like homework,

- Alf
 
S

Salt_Peter

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top