prashna wrote:
Hi all,
Is'nt a function invocation through a function pointer is dynamic
binding?
For example consider the following program
1 int main()
2 {
3 int (*fun_ptr)();
4 int fun(){printf("H IIIIII\n");}
5
6 fun_ptr = fun;
7
8 fun_ptr();
9 return 0;
10 }
OK. I consider (minus the obvious error, of course. C doesn't have
nested functions :-)
Consider the statement at line 8..I guess, which function to be
invoked,at line 8, will be decided at runtime..Is this what is called
as dynamic binding or polymorphism or is it different from
this?
No. In principle you got it.
Polymorphism means that the decision on which function to actually
call is delayed until runtime when the exact type of the object
to use for the call can be determined.
In the above there is no object, it's a plain vanilla function call.
But the principle is the same: The decission which function to call
is delayed until runtime.
Example:
class Animal
{
public:
virtual void MakeNoise() { cout << "Don't know which noise to make\n" );
};
class Dog: public Animal
{
public:
virtual void MakeNoise() { cout << "Wuff, wuff\n" );
};
class Cat: public Animal
{
public:
virtual void MakeNoise() { cout << "Miau, miau\n" );
};
void React( Animal& Pet )
{
Pet.MakeNoise() ;
}
int main()
{
Dog TheDog;
Cat TheCat;
React( TheDog );
React( TheCat );
}
Which MakeNoise() function is called in React(). Just by looking at
the function, nobody can tell. It depends on the exact runtime
type of Pet (Note that Pet is a *reference* to an Animal. Polymorphism
works only with references or pointers). If a Dog object is passed to
React(), then Dog::MakeNoise( ) is called. If a Cat object is passed to
React(), then Cat::MakeNoise( ) is called. The decission which function
to call is delayed until runtime, when the exact runtime type of the
object is known.
Also note: The important syntactic element is the keyword 'virtual' in
the class declarations. It is this keyword, which switches to this
behaviour. Without it Animal::MakeNoi se() would be called in both
cases.
--
Karl Heinz Buchegger
kb******@gascad .at