Page 1 of 1

About virtual

Posted: Wed Jan 11, 2006 4:49 am
by Roby
I'm C programmer and I want to know about C++ language features. Can someone explain to me in clear and easy-to-understand language about these:

a. Can constructor declare using virtual? If yes, what does it mean?

b. Can destructor declare using virtual? If yes, what does it mean?

c. Can we inherit class using virtual? Example:

Code: Select all

class Master
{
 ...
};

class Derived : virtual public Master
{
 ...
};
If yes, what does it mean?

d. What's the difference between:

Code: Select all

virtual void print( void );
and

Code: Select all

virtual void print( void ) = 0;
Thanx in advance :wink:

Re: About virtual

Posted: Wed Jan 11, 2006 4:27 pm
by sumankar
Roby wrote:I'm C programmer and I want to know about C++ language features. Can someone explain to me in clear and easy-to-understand language about these:
Welcome aboard! Caveat: C and C++ are different languages.
Roby wrote: a. Can constructor declare using virtual? If yes, what does it mean?
Short answer no. It can be simulated, though. Read up on virtual construction.
Roby wrote: b. Can destructor declare using virtual? If yes, what does it mean?
Yes, so that destruction via a base class pointer is still valid.
Roby wrote: c. Can we inherit class using virtual? Example:

Code: Select all

class Master
{
 ...
};

class Derived : virtual public Master
{
 ...
};
If yes, what does it mean?
Yes, this is called virtual inheritance. But wait, it is a little different from virtual functions,
and is often used to get over the Diamond-inheritance problem.
Roby wrote: d. What's the difference between:

Code: Select all

virtual void print( void );
This is an ordinary virtual function, so that calls to this through base
class pointers are correctly resolved.
Roby wrote: and

Code: Select all

virtual void print( void ) = 0;
This is a virtual function that also says:
[1] the base class is abstract i.e. cannot instantiate objects of the base class
[2] the derived classes are forced to provide an implementation.

However, even a pure virtual function in the base class can have a body

You need a book on C++. Stroustrup is what you should be looking for. A board/forum
cannot be an alternative to reading, they come handy when you have some understanding
of the topic [ok I'm ready for flames!] And, of course, google.
Also read the c++ faq at http://www.parashift.com/c++-faq-lite

HTH
Suman.

Posted: Thu Jan 12, 2006 8:43 am
by Roby
Thanx a lot Sumankar.
That link you wrote is really helpful.