OOSD Unit5 Part2
OOSD Unit5 Part2
Reaccessability is yet another feature of OOP's. C++ strongly supports the concept of reusability.
The C++ classes can be used again in several ways. Once a class has been written and tested, it can
be adopted by another programmers. This is basically created by defining the new classes, reusing
the properties of existing ones. The mechanism of deriving a new class from an old one is called
'INHERTTENCE'. This is often referred to as IS-A' relationship because very object of the class
being defined "is" also an object of inherited class. The old class is called 'BASE' class and the new
one is called'DERIEVED'class.
Defining Derived Classes
A derived class is specified by defining its relationship with the base class in addition to its own
details. The general syntax of defining a derived class is as follows:
class d_classname : Access specifier baseclass name
{
The following program shows the single inheritance using protected derivation
#include<conio.h>
#include<iostream>
using namespace std;
class worker //Base class declaration
{
protected:
int age;
char name[20];
public:
void get();
void show();
};
void worker::get()
{
cout <<"your name please";
cin >> name;
cout << "your age please";
cin >> age;
}
void worker::show()
{
cout << "in my name is : " << name << "in my age is " << age;
}
class manager:protected worker // protected inheritance
{
int now;
public:
void get();
void show();
};
void manager::get()
{
cout << "please enter the name In";
cin >>name;
cout << "please enter the age In"; //Directly inputting the data
cin >> age; //members of base class
cout << "please enter the no.of workers under you :";
cin >> now;
}
void manager::show()
{
cout << "your name is : " << name << " and age is : " << age;
cout << "In no. of workers under your are : " << now;
}
void main()
{
manager ml;
ml.get();
cout<<"\n \n";
ml.show();
a. Private: when a base class is privately inherited by a derived class, 'public members' of
the base class become private members of the derived class and therefore the public
members of the base class can be accessed by its own objects using the dot
operator. The result is that we have no member of base class that is accessible to the
objects of the derived class.
b. Public: On the other hand, when the base class is publicly inherited, 'public members' of
the base class become 'public members' of derived class and therefore they are
accessible to the objects of the derived class.
c. Protected: C++ provides a third visibility modifier protected, which serve a little
purpose in the inheritance. A member declared as protected is accessible by the
member functions within its class and any class immediately derived from it. It cannot
be accessed by functions outside these two classes.
The below mentioned table summarizes how the visibility of members undergo modifications when
they are inherited
Multilevel Inheritance
When the inheritance is such that, the class A serves as a base class for a derived class B which in
turn serves as a base class for the derived class C. This type of inheritance is called ‘MULTILEVEL
INHERITENCE’. The class B is known as the ‘INTERMEDIATE BASE CLASS’ since it provides a
link for the inheritance between A and C. The chain ABC is called ‘ITNHERITENCE*PATH’ for
e.g.
A Base class
Inheritance path B
Intermediate base class
Derived class
#include<iostream>
#include<conio.h>
using namespace std;
class worker // Base class declaration
{
int age;
char name[20];
public:
void get();
void show();
};
void worker::get()
{
cout << "your name please";
cin >> name;
cout << "your age please";
}
void worker::show()
{
cout << "In my name is : " << name <<"In my age is :" << age;
}
class manager : public worker //Intermediate base class derived
{ //publicly from the base class int now;
public:
void get();
void show();
};
void manager::get()
{
worker::get(); //calling get ( ) fn. of base class cout << “no. of workers under you:”;
cin >>now;
}
void manager::show()
{
worker::show(); //calling show ( ) fn. of base class cout << “In no. of workers under me are: “<< now;
}
class ceo : public manager //declaration of derived class
{ //publicly inherited from the
int nom; //intermediate base class public:
void get(); void show();
};
void ceo::get()
{
manager::get();
cout << "no.of managers under you are :"; cin >> nom;
}
void manager::show()
{
cout <<"In the no.of managers under me are : In"; cout << “nom;
}
main()
{
ceo c1;
c1.get(); cout << "\n\n"; c1.show();
}
Worker
Private:
int age;
char name[20];
Protected:
Private:
int age;
char name[20];
Manager:Worker
Private:
int now;
Protected:
Public:
void get()
void show()
worker ::get()
worker ::get()
Ceo: Manager
Public:
Protected:
Public:
All the
inherited
members
Multiple Inheritances
A class can inherit the attributes of two or more classes. This mechanism is known as ‘MULTIPLE
INHERITENCE’. Multiple inheritances allows us to combine the features of several existing classes
as a starring point for defining new classes. It is like the child inheriting the physical feature of one
parent and the intelligence of another. The syntax of the derived class is as follows:
where the visibility refers to the access specifiers i.e. public, private or protected. Following
program shows the multiple inheritance.
#include<iostream.h>
#include<conio . h>
class father //Declaration of base classl
{
int age ;
char flame [20] ;
public:
void get ( ) ;
void show ( ) ;
};
void father : : get ( )
{
cout << “your father name please”;
cin >> name;
cout << “Enter the
age”; cin >> age;
}
void father : : show ( )
{
cout<< “In my father’s name is: ‘ <<name<< “In my father’s age is:<<age;
}
class mother //Declaration of base class 2
{
char name [20] ;
int age ;
public:
void get ( )
{
cout << “mother’s name please” <<
“In”; cin >> name;
cout << “mother’s age please” <<
“in”; cin >> age;
}
void show ( )
{
cout << “In my mother’s name is: “
<<name; cout << “In my mother’s age is: “
<<age;
}
class daughter : public father, public mother //derived class inheriting
{ //publicly
char name [20] ; //the features of both the base
class int std;
public:
void get ( ) ;
void show ( ) ;
};
void daughter :: get ( )
{
father :: get ( ) ;
mother :: get ( ) ;
cout << “child's name:
“; cin >> name;
cout << “child's
standard”; cin >> std;
}
void daughter :: show ( )
{
father :: show ( );
nfather :: show ( ) ;
cout << “In child’s name is : “
<<name; cout << “In child's standard: “
<< std;
}
main ( )
{
clrscr ( ) ;
daughter d1;
d1.get ( ) ;
d1.show ( ) ;
}
Private: Private:
int age; int age;
char name[20]; char name[20];
Protected: Protected:
Public: Public:
void get() void get()
void void
show() show()
Protected:
Public:
//self
void get(); void showQ;
//from Father
void get(); void show();
//from Mother
void get(); void show();
Hierarchical Inheritance
Another interesting application of inheritance is to use is as a support to a hierarchical design of a
class program. Many programming problems can be cast into a hierarchy where certain features of
one level are shared by many others below that level for e.g.
Accounts
Fixed deposit
Mid term
Class A
{
// body A
}
In C++, such problems can be easily converted into hierarchies. The base class will include all the
features that are common to the subclasses. A sub-class can be constructed by inheriting the features
of base class and so on.
#include<iostream>
#include<conio.h>
using namespace std;
class father //Declaration of base classl
{
int age;
char flame[20];
public:
void get();
void show();
};
void father::get()
{
cout << "your father name please";
cin >> name;
cout << "Enter the age";
cin >> age;
}
void father::show()
{
cout << "In my father’s name is :" << name << "In my father’s age is :"; << age;
}
class mother //Declaration of base class 2
{
char name[20];
int age;
public:
void get()
{
cout << "mother’s name please" << "In";
cin >> name;
cout << “mother’s age please” << “in”;
cin >> age;
}
void show()
{
cout << “In my mother’s name is : “ << name;
cout << “In my mother’s age is : “ << age;
}
class daughter : public father, public mother //derived class inheriting
{ //publicly
char name[20]; //the features of both the base class
int std;
public:
void get();
void show();
};
void daughter::get()
{
father::get();
mother::get();
cout << “child's name: “;
cin >> name;
cout << “child's standard”;
cin >> std;
}
void daughter::show()
{
father::show();
nfather::show();
cout << “In child’s name is : “ << name;
cout << “In child's standard: “ << std;
}
main()
{
daughter d1;
d1.get();
d1.show();
}
Hybrid Inheritance
There could be situations where we need to apply two or more types of inheritance to design a
program. Basically Hybrid Inheritance is the combination of one or more types of the inheritance.
Here is one implementation of hybrid inheritance.
public :
void get_m (int x, int y) {
parti = x; part 2 = y; }
void put_m (void) {
cout << “marks obtained: “ << “In”
<< “Part 1 = “ << part1 << “in”
<< “Part 2 = “ << part2 << “In”;
}
};
class sports // base for result
{
protected : int score;
public:
void get_s (int s) {
score = s }
void put_s (void) {
cout << “ sports wt. : “ << score << “\n\n”;
}
};
class result : public test, public sports //Derived from test
& sports
{
int total;
public:
void display (void);
};
clrscr ( ) ;
result S1;
S1.get_n (347) ;
S1.get_m (30, 35);
S1.get_s (7) ;
S1.dciplay ( ) ;
}
Let us say the 'child' has two direct base classes ‘parent1’ and ‘parent2’ which themselves has a
common base class ‘grandparent’. The child inherits the traits of ‘grandparent’ via two separate
paths. It can also be inherit directly as shown by the broken line. The grandparent is sometimes
referred to as ‘INDIRECT BASE CLASS’. Now, the inheritance by the child might cause some
problems. All the public and protected members of ‘grandparent’ are inherited into ‘child’ twice, first
via ‘parent1’ and again via ‘parent2’. So, there occurs a duplicacy which should be avoided.
The duplication of the inherited members can be avoided by making common base class as the
virtual base class: for e.g.
class g_parent
{
//Body
};
class parent1: virtual public g_parent
{
// Body
};
When a class is virtual base class, C++ takes necessary care to see that only one copy
of that class is inherited, regardless of how many inheritance paths exists between
virtual base class and derived class. Note that keywords ‘virtual’ and ‘public’ can be
used in either order.
protected:
int y ;
public:
};
};
Polymorphism:
Introduction
When an object is created from its class, the member variables and member functions are allocated
memory spaces. The memory spaces have unique addresses. Pointer is a mechanism to access these
memory locations using their address rather than the name assigned to them. You will study the
implications and applications of this mechanism in detail in this chapter.
Pointer is a variable which can hold the address of a memory location rather than the value at the
location. Consider the following statement
This statement instructs the compiler to reserve a 2-byte of memory location and puts the value 84 in
that location. Assume that the compiler allocates memory location 1001 to num. Diagrammatically,
the allocation can be shown as:
84 Value
Figure 9.1
As the memory addresses are themselves numbers, they can be assigned to some other variable For
example, ptr be the variable to hold the address of variable num.
Thus, we can access the value of num by the variable ptr. We can say “ptr points to num” as shown
in the figure below.
num num
84 1001
1001 2057
Fig 9.2
Pointers to Objects
An object of a class behaves identically as any other variable. Just as pointers can be defined in case
of base C++ variables so also pointers can be defined for an object type. To create a pointer variable
for the following class
class employee {
int code;
char name [20] ;
public:
inline void getdata ( )= 0 ;
inline void display ( )= 0 ;
};
The following codes is written
employee *abc;
This declaration creates a pointer variable abc that can point to any object of employee type.
this Pointer
C++ uses a unique keyword called "this" to represent an object that invokes a member function. 'this'
is a pointer that points to the object for which this function was called. This unique pointer is called
and it passes to the member function automatically. The pointer this acts as an implicit argument to
all the member function, for e.g.
class ABC
{
int a ;
};
The private variable ‘a’ can be used directly inside a member function, like
a=123;
We can also use the following statement to do the same job.
this → a = 123
e.g.
class stud
{
int a;
public:
void set (int a)
{
this → a = a; //here this point is used to assign a class level
} ‘a’ with the argument ‘a’
void show ( )
{
cout << a;
}
};
main ( )
{
stud S1, S2;
S1.bet (5) ;
S2.show ( );
}
o/p = 5
class base
{
//Data Members
//Member Functions
};
class derived : public base
{
//Data Members
//Member functions
};
void main ( ) {
base *ptr; //pointer to class base
derived obj ;
ptr = &obj ; //indirect reference obj to the pointer
//Other Program statements
}
The pointer ptr points to an object of the derived class obj. But, a pointer to a derived class object
may not point to a base class object without explicit casting.
Late Binding
As we studied in the earlier unit, late binding means selecting functions during the execution.
Though late binding requires some overhead it provides increased power and flexibility. The late
binding is implemented through virtual functions as a result we have to declare an object of a class
either as a pointer to a class or a reference to a class.
For example the following shows how a late binding or run time binding can be carried out with the
help of a virtual function.
class base {
private :
int x;
float y;
public:
virtual void display ( ) ;
int sum ( ) ;
};
class derivedD : public baseA
{
private :
int x ;
float y;
public:
void display ( ); //virtual
int sum ( ) ;
};
void main ( )
{
baseA *ptr ;
derivedD objd ;
ptr = &objd ;
Other Program statements
ptr- >di splay ( ) ; //run time binding ptr-
>sum ( ) ; //compile time binding
}
Note that the keyword virtual is be followed by the return type of a member function if a run time is
to be bound. Otherwise, the compile time binding will be effected as usual. In the above program
segment, only the display ( ) function has been declared as virtual in the base class, whereas the sum
( ) is nonvirtual. Even though the message is given from the pointer of the base class to the objects of
the derived class, it will not
access the sum ( ) function of the derived class as it has been declared as nonvirtual. The sum ( )
function compiles only the static binding.
The following program demonstrates the run time binding of the member functions of a class. The
same message is given to access the derived class member functions from the array of pointers. As
function are declared as virtual, the C++ compiler invokes the dynamic binding.
#include <iostream.h>
#include <conio.h>
class baseA {
public :
virtual void display () {
cout<< “One \n”;
}
};
class derivedB : public baseA
{
public:
virtual void display(){
cout<< “Two\n”; }
};
class derivedC: public derivedB
{
public:
virtual void display ( ) {
cout<< “Three \n”; }
};
void main ( ) {
//define three objects
baseA obja;
derivedB objb;
derivedC objc;
base A *ptr [3]; //define an array of pointers to baseA
ptr [0] = &obja;
ptr [1] = &objb;
ptr [2] = &objc;
for ( int i = 0; i <=2; i ++ )
ptr [i]->display ( ); //same message for all objects
getche ( ) ;
}
Output
One
Two
Three
The program listed below illustrates the static binding of the member functions of a class. In program
there are two classes student and academic. The class academic is derived from class student. The
two member function getdata and display are defined for both the classes. *obj is defined for class
student, the address of which is stored in the object of the class academic. The functions getdata ( )
and display ( ) of student class are invoked by the pointer to the class.
#include<iostream.h>
#include<conio.h>
class student {
private:
int rollno;
char name [20];
public:
void getdata ( );
void display ( );
};
class academic: public student {
private:
char stream;
public:
void getdata ( );
void display ( ) ;
};
void student:: getdata ( )
{
cout<< “enterrollno\n”;
cin>>rollno;
cout<< “enter name \n”;
cin>>name;
}
void student:: display ( )
{
cout<< “the student’s roll number is “<<rollno<< “and name is”<<name ;
cout<< endl;
}
void academic :: getdata ( )
{
cout<< “enter stream of a student? \n”;
cin >>stream;
}
void academic :: display ( ) {
cout<< “students stream \
n”; cout <<stream<< endl;
}
void main ( )
{
student *ptr ;
academic obj
; ptr=&obj;
ptr->getdata ( ) ;
ptr->display ( ) ;
getche ( );
}
output
enter rollno
25
enter name
raghu
the student’s roll number is 25 and name is raghu
The program listed below illustrates the dynamic binding of member functions of a class. In this
program there are two classes student and academic. The class academic is derived from student.
Student function has two virtual functions getdata ( ) and display (). The pointer for student class is
defined and object . for academic class is created. The pointer is assigned the address of the object
and function of derived class are invoked by pointer to student.
#include <iostream.h>
#include <conio.h>
class student {
private:
introllno;
char name [20];
public:
virtual void getdata ( );
virtual void display ( );
};
class academic: public student {
private :
char stream[10];
public:
void getdata { };
void display ( ) ;
};
void student: : getdata ( )
{
cout<< “enter rollno\n”;
cin >> rollno;
cout<< “enter name \n”;
cin >>name;
}
void student:: display ( )
{
cout<< “the student’s roll number is”<<rollno<< “and name is”<<name;
cout<< end1;
}
void academic: : getdata ( )
{
cout << “enter stream of a student? \n”;
cin>> stream;
}
void academic:: display ( )
{
cout<< “students stream \n”;
cout<< stream << endl;
}
void main ( )
{
}
output
student *ptr ; academic obj ; ptr
= &obj ; ptr->getdata ( ); ptr-
>dlsplay ( ); getch ( );
enter stream of a student?
Btech
students stream
Btech
LECTURE-32
The following program demonstrates how a pure virtual function is defined, declared and invoked
from the object of a derived class through the pointer of the base class. In the example there are two
classes employee and grade. The class employee is base class and the grade is derived class. The
functions getdata ( ) and display ( ) are declared for both the classes. For the class employee the
functions are defined with empty body or no code inside the function. The code is written for the
grade class. The methods of the derived class are invoked by the pointer to the base class.
#include<iostream.h>
#include<conio.h>
class employee {
int code
char name [20] ;
public:
virtual void getdata ( ) ;
virtual void display ( ) ;
};
class grade: public employee
{
char grd [90] ;
float salary ;
public :
void getdata ( ) ;
void display ( );
};
void employee :: getdata ( )
{
}
void employee:: display ( )
{
}
void grade : : getdata ( )
{
cout<< “ enter employee’s grade “;
cin> > grd ;
cout<< “\n enter the salary “ ;
cin>> salary;
}
void grade : : display ( )
{
cout«" Grade salary \n";
cout« grd« " "« salary« endl;
}
void main ( )
{
}
Output
employee *ptr ; grade obj ;
ptr = &obj ;
ptr->getdata ( ) ; ptr->display
( ) ; getche ( ) ;
enter employee’s grade
A enter the salary
250000 Grade salary
A 250000