Joined: Sun Oct 19, 2008 3:47 pm Posts: 281 Has thanked: 0 time Have thanks: 1 time
What actually facilitates the late binding in run time polymorphism?
Is it only the keyword VIRTUAL?
because for example
Code:
#include ....
class A { public: virtual void display () = 0; };
class B: public A { public: void display () { cout << "B"; } };
class C: public A { public: void display () {cout <<"C";} };
void main() { A a; B b; C c; A * ptr[3]; ptr[0] = &a; ptr[1] = &b; ptr[2] = &c;
ptr[1]-> display(); //What's so run time about this? }
I mean, it is known quite well that ptr[1] points to an object of type B, this information is, according to what i think, available at compile time. Or does the keyword VIRTUAL change everything? and if that's so, what's the advantage of it run time polymorphism over compile time polymorphism???
AnswerBot
Question subject: Re: run time polymorphism
Posted: Sat Nov 08, 2008 3:31 pm
Joined: Sun Oct 19, 2008 3:53 pm Posts: 229 Has thanked: 0 time Have thanks: 0 time
You've made the #1 mistake of base/derived classes: You forgot the virtual destructors. Get in the habit of including them even for cheesy examples.
To answer your question: You can pass a derived class to a function that takes a base class as its input. That function can then call the derived methods by calling the base class methods of the same name and numbers and types of parameters. However, abstract classes (i.e. where you declare functions in a class 'virtual ...() = 0') are much more annoying to deal with in this manner.