Object Orientation
Object Orientation
Templates
• Is Class generic enough?
savings_account current_account
joint_savings_ account
Virtual Functions
class account{
class joint_savings_account:public
protected:
savings_account
public:
virtual void print() { } {
}; protected:
class savings_account:public account public:
{
protected: // print additional members
public: declared in this class
// print additional members virtual void print() { }
declared in this class
};
virtual void print() { }
};
Virtual Functions Cont..
We keep an additional field (a) for type of an object within each node
of the list.
S J A
•Offset of D (derived class object) will have all fields which are there in
B (base class object) followed by its own fields.
Virtual Functions Cont..
• Example:
account *pa ;
while(h!=NULL){
pa= h->object;
switch(h->type) { // type of account
Case 'A' : pa->account::print();
break;
Case 'S': pa->savings_account::print();
}
h=h->next;
}
Type Maintenance by Language
• Can type maintenance be done by Language itself?
• Then,
while(h!=NULL)
{
pa =h->object;
pa->print(); // which print() to call, language will find out the type of object
h=h->next; being pointed and then decide which function to call.
}
Solution:
•Dynamic Method Binding supported by OOP and is supported in C++ using virtual
functions.
Implementation of Dynamic Binding
• Keep the type of object along with the object. •If it encounters a base class
• Example: virtual table (vtab) pointer and print( ) is called
using it, pa->print(), then vtab
Points to code
of object of that type is used.
segment of the
account function that is to be
name called at run time. • pa might point to derived
account::print( )
balance class object.
Points to code
segment of the
account function that is to be
called at run time.
name savings_account::pri
nt( )
balance
interest_
rate
Implementation of Dynamic Binding
class bar: public foo{ bar pointer to
bar::vtab bar::k( )
protected: vtab
a
int w; foo::l( )
int m( ) { } d foo::n( )
double x( ) { }
• k(), l(), m() and n() are at same index level.
} • Any function that is virtual in any of the
• m( ) becomes final, can not be base classes will be kept in vtab of derived
overriden further.
class. Ex. foo::l( ) because the indices in
vtab won't get disturbed.
• x( ) will not be in vtab • All objects of given class store the same virtual
table.