Object Oriented Programming 3
Object Oriented Programming 3
Polymorphism
• Combination of two Greek words
• Poly (many) morphism (form)
Static Polymorphism/
Dynamic Polymorphism/
Static Binding
Dynamic Binding
3
Binding Process
• Binding is the process to associate variable/
function names with memory addresses
Start address if
sayHi() function
5
Run-time Binding (Dynamic Binding)
• Run-time binding is to associate a function's name with
the entry point (start memory address) of the function
at run time (also called late binding)
SomeClass obj1;
// The first 'func' is called
obj1.func(7);
8
Pointers to Derived Classes
• C++ allows base class pointers or references to
point/refer to both base class objects and also all
derived class objects.
• Let’s assume:
class Base { … };
class Derived : public Base { … };
base b1;
derived *pd = &b1; // compiler error
10
Pointers to Derived Classes (contd.)
• Access to members of a class object is determined
by the type of
– An object name (i.e., variable, etc.)
– A reference to an object
– A pointer to an object
11
Pointers to Derived Classes (contd.)
• Using a base class pointer (pointing to a derived
class object) can access only those members of the
derived object that were inherited from the base.
void main() {
//pointer of class type A points to
//object of child class B
A* a = new B;
a->foo(); //ERROR
}
15
Summary – Based and Derived Class
Pointers
• Base-class pointer pointing to base-class object
– Straightforward
• The first class that defines a virtual function is the base class of the
hierarchy that uses dynamic binding for that function name and
signature.
22
Virtual function
class A {
public:
virtual void func() {
cout << "A's func" << endl;
}
};
class B:public A {
public:
void func() { //automatically virtual
//use override keyword to ensure parameters match
cout << "B's func" << endl;
}
};
void main() {
B b;
//pointer of class type A points to
//object of child class B
A* a = &b;
a->func(); //calls B's func
}
23
Virtual function with Multilevel
class A {
public:
Inheritance
virtual void func() {
cout << "A's func" << endl;
}
};
class B:public A {
public:
void func() { //automatically virtual
//use override keyword to ensure parameters match
cout << "B's func" << endl;
}
};
class C :public B {
public:
void func() { //automatically virtual
//use override keyword to ensure parameters match
cout << "C's func" << endl;
}
};
void main() {
//pointer of class type A points to
//object of grandchild class C
A* a = new C;
a->func(); //calls C's func
} 24