Wednesday, January 23, 2008

Virtual Function

virtual = overridable, dynamic binding, called at runtime

Without virtual destructor

class Base {
public:
~Base();
};

Base::~Base()
{}

void unawareOfDerived(Base* base)
{ delete base; }

class Derived : public Base {
public:
~Derived();
};

Derived::~Derived()
{}

int main()
{
Base* base = new Derived();
unawareOfDerived(base);
}
Derived destructor will not run.
The virtual keyword cannot be applied to a constructor since a constructor turns raw bits into a living object, and until there is a living object against which to invoke a member function, the member function cannot possibly work correctly.(from C++ FAQs 21.07)

A pure virtual member function is a member function that the base class forces derived classes to provide (give an interface). A pure virtual member function specifies that a member function will exist on every object of a concrete derived class even though the member function is not (normally) defined in the base class.

For example, all objects of classes derived from Shape will have the member function draw(). However, because Shape is an abstract concept, it does not contain enough information to implement draw(). Thus draw() should be a pure virtual member function in Shape.

class Shape {
public:
virtual void draw() = 0;
};

This pure virtual function makes Shape an abstract base class (ABC). Imagine that the "= 0" is like saying "the code for this function is at the NULL pointer."
--
check the former post VTable and Size of class (update Jan. 31, 08)

No comments:

Post a Comment