WittyGuy said:
Hi,
I wonder the necessity of constructor and destructor in a Abstract
Class? Is it really needed?
Absolutely. You can't create a class without a constructor or without
a destructor. (If you don't specify one, the compiler will do it for
you.)
I suspect that by "Abstract Class" you mean a class with just pure
virtual functions and no data members. Note that C++ allows base
classes with data members and real member functions.
I think you meant to ask about user specified constructors and
destructors. If so, there is no overriding need for a user specified
constructor (though of course, a particular class might benefit from
one - particularly if the class has data members which need
initializing).
In the case of a destructor I would be very surprised if you didn't
want to declare one. The problem is that the compiler generated
destructor will be public and non-virtual (assuming the class in
question has no bases with virtual destructors). This means there is
nothing to stop someone doing:
delete pAbstractClass;
where the actual object pointed at is of some derived type. If the
destructor is not virtual this is "undefined behaviour", which
basically means "bad things may happen".
There are two ways (I know of) to avoid the bad things. One is to
declare a virtual destructor (which avoids the bad things), the other
is to make the destructor protected (which makes the statement a
compilation error). Both of these methods require the destructor to be
declared.
There is less point making the destructor PURE virtual though (provided
at least one other function is pure virtual). A pure virtual function
a) has to be overriden by a derived class (but destructors have to be
overriden anyway); b) prevent the base class from being instantiated as
a specific object (but another pure virtual function will do that
anyway).
The other thing about pure virtual functions is that they don't need to
be implemented (although they can be). The exception is the destructor
- even if the destructor is pure virtual, it has to be implemented
(somewhere).
that means
[ See
http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]