You are on page 1of 49

UNIT IV

PROGRAMMING IN C AND C++ - SCSA1202

1
I. OBJECT ORIENTED PROGRAMMING CONCEPTS
Introduction-Procedure vs. object-oriented programming-Concepts: Classes and Objects-
Operator & Function Overloading-Inheritance-Polymorphism and Virtual Functions.

Object Oriented Programming Paradigms


Software evolution

Fig.4.1 Layers of Computer Software


Since the invention of the computer, many programming approaches have been tried. These
include techniques such as modular programming and structured programming. The primary
motivation in each has been the concern to handle the increasing complexity of programs that
are reliable and maintainable. These techniques have been popular among programmers over
the last two decades.
Machine language:
It is the lowest-level programming language. Machine languages are the only languages
understood by computers. While easily understood by computers, machine languages are
almost impossible for humans to use because they consist entirely of numbers.
Assembly language:
Machine language is almost impossible for humans to understand. Programmers, therefore,
use either a high-level programming language or an assembly language. An assembly
language contains the same instructions as a machine language, but the instructions and
variables have names instead of being just numbers.
Procedure-oriented Programming:
The high level languages, such as BASIC, COBOL, C, FORTRAN are commonly known as
Procedure Oriented Programming. Using this approach, the problem is viewed in sequence of

2
things to be done, like reading, processing and displaying or printing. To carry out these tasks
the function concepts must be used.

Fig.4.2 Typical Structure of Procedure Oriented Programs


This concept basically consists of number of statements and these statements are organized or
grouped into functions.
While developing these functions the programmer must care about the data that is being
used in various functions.
A multi-function program, the data must be declared as global, so that data can be accessed
by all the functions within the program & each function can also have its own data called
local data.

Fig.4.3.Relationship of data and functions in procedural programming


The global data can be accessed anywhere in the program. In large program it is very difficult
to identify what data is accessed by which function. In this case we must revised about the
external data and as well as the functions that access the global data. At this situation there is
so many chances for an error.
Characteristics of Procedure-oriented Programming (C):
• Emphasis is on doing things (algorithms).
• Larger programs are divided into smaller programs known functions.
• Most of the functions share global data.
• Data move openly around the system from function to functions.
• Functions transform data from one form to another
• Employs TOP-DOWN approach in program design.

3
Object-oriented programming
• This programming approach is developed to reduce the some of the drawbacks
encountered in the Procedure Oriented Programming approach.
• The OOProgramming approach treats data as critical element and does not allow the
data to flow freely around the program.
• It bundles the data more closely to the functions that operate on it; it also protects data
from the accidental modification from outside the function.
• The object oriented programming approach divides the program into number of
entities called objects and builds the data and functions that operate on data around
the objects.
• The data of an object can only access by the functions associated with that object.
However the functions of one object can access the functions of other objects.

Fig.4.4 Organisation of data and functions in OOP


Characteristics of Object-oriented Programming (C++):
• Emphasis is on data rather than procedure.
• Programs are divided into what known as OBJECTS
• Data structures are designed such that they characterize the objects
• Functions that operate on the data of an object are tied together in the data structure.
• Data is hidden and cannot be accessed by external functions.
• Objects may communicate with each other through functions
• New data and functions can be easily added whenever necessary
• Follows BOTTOM-UP approach in program design.

4
Comparison of Programming Paradigms:
Difference between C & C++ C is an procedure oriented programming language, whereas
C++ is an object oriented programming language. The need for an object oriented
environment is because procedure oriented programming language such as C fails to show
the desired results for larger programs inters of bug free, complexity & reusable programs.
C++ eliminates the pitfalls faced by C language. There are many differences which makes
C++ as an apt alternative to C. There are many concepts in C++ which C language doesn’t
support. They are data hiding, data encapsulation, inheritance, polymorphism, classes,
objects, operator overloading & message passing. These concepts can eliminate the
complexity of C for larger programs.
The main difference between C & C++ is where we use the class (user defined data type),
Through class we derive the other concepts. Class is similar to structure in C. In structure
only mixed data type can be declared, whereas C++ allows us to declare & define functions
in addition to the data's. This makes the main function more simple & grouping all functions
into a single class.
Operator overloading concept in C++ makes us to create a new language of or own. Through
this we can perform arithmetic an operation on variables of class i.e. objects which makes the
program easier to understand. In C we can’t perform arithmetic operation on structure
variable as we do in C++.
In c for larger programs the presence of redundant codes is unavoidable. This can be
eliminated in C++ by following inheritance.
In C there may be accidental invading of codes of one program by another program. This can
be eliminated in C++ which supports data hiding which helps the programmer to build secure
programs that cannot be invaded by code in other parts of the program.
In C, if we want to add additional features to the program without modifying the function is
very difficult. This can be eliminated in C++ which supports inheritance where we can add
additional features to an existing class without modifying it. This concept provides the idea of
reusability of the programs.
Table.4.1 Comparison Between Procedure Oriented and Object Oriented Programming
S.No Procedure oriented Programming(C) Object Oriented Programming (C++)

1 Programs are divided into smaller sub- Programs are divides into objects &classes
programs known as functions
2 Here global data is shared by most of Objects are easily communicated with each
the functions other through functions.
3 Follows Top-Down Approach Follows Bottom-Up Approach

4 Data cannot be secured and available to Data can be secured and can be available in
all the functions. the class in which it is declared.
5 Here, the reusability is not possible; Here, we can reuse the existing one using

5
hence redundant code cannot be the Inheritance concept.
avoided.

Object oriented Languages:


Object oriented programming languages are divided into two.
They are
1. Object based programming languages
2. Object oriented programming languages
Object based programming:
Languages that support programming with objects are said to be Object based programming
languages. They do not inheritance and Dynamic binding. Object based programming is the
style of programming that supports encapsulation and identity.
Major features that are required for this are:
1. Data Encapsulation
2. Data hiding and access mechanism
3. Automatic initialization and clear up of objects
4. Operator overloading Object oriented programming
Object oriented programming includes all features of Object based programming with two
additional features like inheritance and Dynamic binding.
Benefits or Advantages of OOP’s
• The complexity of software can be managed easily.
• Data hiding concept help the programmer to build secure programs
• Through the class concept we can define the user defined data type
• The inheritance concept can be used to eliminate redundant code
• The message-passing concept helps the programmer to communicate between
different objects.
• New data and functions can be easily added whenever necessary.
• OOP’s ties data elements more closely to the functions that operate on.
Application of OOP
• Real-time system
• Simulation and modelling
• Object-oriented database
• Hypertext, hypermedia and expertext
• Artificial intelligence and expert system
• Neural network and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD system
6
COMPARISON of C with C++
C Language
• Top Down approach
• Procedure oriented
• Variables cannot be dynamically initialised
• Reference variables concept is not there
• Memory management
o Allocation: malloc(), calloc()
o Deallocation: free()
• Type casting: Syntax: (typename) expression
• Object Oriented concepts like Inheritance, polymorphism, dynamic binding,
encapsulation etc are not supported
• There is no inline function or friend function
• Input and output:
o Scanf() and printf() library functions are used for reading input and writing
output respectively.
• There is no scope resolution operator to access the global variables in the interior
blocks of the functions
• Constructors and destructors are not used
• Object oriented concepts like inheritance, polymorphism, encapsulation, dynamic
binding etc are not supported.
C++ Language
• Bottom up approach
• Object oriented
• Allows dynamic initialisation of variables
Eg: cin>>str;
int len=strlen(str);
• Uses reference variables
Eg: float tot=100
float & sum=tot;
// Here the reference variable sum references the variable tot
• Memory management
o Allocation: new operator is used
o Deallocation: delete operator is used
• Type casting:
Syntax: type name (expression)
• Inline functions: an inline function is a function upon which the compiler has been
requested to perform inline expansion.

Eg: #include<iostream.h>
class inl
{public:
inline int cube(int a)
return a*a*a;
};
Int main()

7
{inl o;
int c=o.cube(3);
return 0;
}

o Input and output:


• >> Extraction operator for reading input
• << Insertion operator for printing the output
• Eg: cin>> a;
• cout<<a;
o Scope resolution operator:
The scope resolution operator helps to identify and specify the context to
which an identifier refers.
Syntax: ::member_name
o Friend functions and virtual functions are used
o Constructors and destructors are not used
o Object oriented concepts like inheritance, polymorphism, encapsulation,
dynamic binding etc are supported.
Overview of C++ Programming
C++ was developed by BJARNE STROUSSTRUP at AT&T BELL Laboratories
in Murry Hill, USA in early 1980’s.
Striysstryo combines the features of ‘C’ language and ‘SIMULA67’ to create
more powerful language that support OOPS concepts, and that language was
named as “C with CLASSES”. In late 1983, the name got changed to C++.
The idea of C++ comes from ‘C’ language increment operator (++) means more
additions.
C++ is the superset of ‘C’ language, most of the ‘C’ language features can also
applied to C++, but the object oriented features (Classes, Inheritance,
Polymorphism, Overloading) makes the C++ truly as Object Oriented
Programming language.
Structure of C++ Program

Fig.4.5 Structure of C++ Program


Include files provides instructions to the compiler to link functions from the systemlibrary.
Eg: #include <iostream.h>

8
#include – Preprocessor Directive
iostream.h – Header File
➢ A class is a way to bind and its associated functions together. It is a user
defineddatatype. It must be declared at class declaration part.
➢ Member function definition describes how the class functions are implemented.
Thismust be the next part of the C++ program.
➢ Finally main program part, which begins program execution.
main( )
{

}
➢ Program execution begins at the opening brace and ends at the closing brace.
Theclosing brace of the main function is the logical and of the program.
➢ Input / Output statements
Input Stream:
Syntax:cin >> var1 >> var2 >>;cin – Keyword, it is an object, predefined in C++ to
correspond to the standard inputstream.
>> - is the extraction or get from operator.
Extraction operation (>>) takes the value from the stream object on its left and places
itin the variable on its right.
Eg:cin>>x;cin>>a>>b>>c;

Output Stream:
Syntax:cout<<var1<<var2;
cout - object of standard output stream
<< -is called the insertion or put to operator.
It directs the contents of the variable on its right to the object on its left.Output stream
can be used to display messages on output screen.
Eg:cout<<a<<b;cout<<”value of x is”<<x;cout<<”Value of x is”<<x<<”less
than”<<y;

Basic concepts of OOP’s


• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
Classes and Objects
The most important feature of C++ is the “class”. A class is an extension of the idea of
structure used in C. it is a new way of creating and implementing a user-defined data
type.OOP constructs modelled out of data types called classes. Defining variables of a class
data type is known as a class instantiation and such variables are called objects. (Object is an
instance of a class.)

9
Fig.4.6 Class grouping of data and functions
Placing data and functions together in a single unit is the central theme of the OOP. The
programmers are entirely responsible for creating their own classes and can also have access
to classes developed by the software vendors. The variables and functions enclosed in a class
are called data members and member functions respectively. Member functions define the
permissible operations on the data members of a class.
Classes are the basic language construct of C++ for creating the user-defined data types. They
are syntactically extension of structures. The difference is that, all the members of structures
are public by default whereas, the members of classes are private by default. Class follows
the principle that the members should be private unless it is specifically declared public.
Objects:
• Objects are the basic run time entities in an object-oriented system.
• Each entity can be treated as object. Object contains data and code to
manipulate these data’s.
• They may represent a person, a place, a bank account, a table of data or
any item with which the computer must deal or handle.
• Some objects may correspond to real-world entities such as students,
employees, bank accounts, etc.
• Every object will have a state called attributes (data) and the behaviour
called operations (function).
When a program is executed, the objects interact by sending messages to one another .For
example, if ‘customer’ and ‘account’ are the two objects in a program, then the customer
object may send a message to the account object. Each object contains data and code to
manipulate the data. Objects can interact without having to know details of each other data
or code. It is sufficient to know the type of message accepted, and the type of response
returned by the objects.

10
Fig.4.7 Two ways of representing an object
Desktop lamp may have only two possible states (on and off) and two possible behaviours
(turn on, turn off), but your desktop radio might have additional states (on, off, current
volume, current station) and behaviour (turn on, turn off, increase volume, decrease
volume, seek, scan, and tune).

Fig.4.8. Example for an Object


• Each object will have its own identity though its attributes and operations are same,
the objects will never be equal.
• For example in case of a person object, two persons will have same attributes like
name, age, sex; but they are not equal.

11
Classes
• We know that objects contain data and function or code to manipulate that data. The
entire set of data and code of an object can be made a user-defined data type with the
help of a class.
• Objects are variables of type class.
• Classes are user defined data types and behaves like the built-in types of a
programming language.
• Once a class has been defined, we can create any number of objects associated with
that class.
• Thus, a class is collection of objects of similar type i.e., the objects with the same
state (attributes) and behaviour (operations) are grouped into a class.
• For example, mango, apple and orange are members of class fruit.
• The syntax used to create an object is no different from the syntax used to create an
integer object in C.
• If fruit has been defined as a class, then the statement
Eg: fruit mango; will create an object mango belonging to the class fruit.
Class specification
A class is a way to bind the data and its associated functions together. It allows the data (and
functions) to be hidden, if necessary, from external use.
A class specification has two parts:
1. Class declaration
2. Class function definitions
The class declaration describes the type and the scope of its members. The class function
definitions describe how the class functions are implemented.
The general form of a class declaration is:

Fig.4.9. Example for an Object


The class declaration is similar to a struct declaration. The keyword class specifies that what
follows is an abstract data of type class_name. The body of the class is enclosed within
braces and terminated by a semicolon. The class body contains the declarations of variables
and functions. These variables and functions are collectively known members. They are

12
usually grouped under two sections namely private and public to denote which of them are
members of private and public. The keywords private and public and private are known as
visibility labels. Note that these keywords are followed by a colon (:).
The members that have been declared as private can be accessed only from within the class.
From the other hand the public members can be accessed from outside the class also. The
data hiding is the key future of object oriented programming.
The use of the keyword private is optional; by default the members of the class are private. If
both the labels are missing, then by default, all the members are private. Such a class is
completely hidden from the outside world.
The variables which are declared inside the class are known as data members and the
functions are known as member functions. Only the member functions can have access to the
private data members and private functions. The binding of data and functions together into a
single class_type variable is referred to as encapsulation.
A simple example for class
Class item
{
int number; //variables declared in the
float cost;//private section
public:
void getdata();//function declared in public section
void putdata();//function declared in public section
};
class is given some meaningful name, such as item . The class contains two data members
and two function members. The data members are private by default. The function getdata( )
can be used to read values for number and cost and putdata( ) to print the values. Note that
the function is declared and not defined. Actually the function definition appears after the
program. The data members are usually declared as private and the member functions as
public.
Creating objects (Class Objects)
The above example class item shows what that class will contain, if we want to create an
object of that class, we must use the class name in such a way.
Item x; //memory for x is created
Which creates a variable x of type item. In C++, the class variables are known as objects.
Therefore x is called as an object of type item. We may also declare more than one object in
one statement.
Eg: Item x,y,z;

13
The declaration of an object is similar to that of variables of any basic data type.
Objects can also be created by placing the objects name immediately after the closing brace,
as we do in the case of structures. That is, the definition
Class item
{........
...........
...........}
x, y , z ;
would create the objects x,y,z of type item.
Accessing class members:
As pointed out earlier, the private data of a class can be accessed only through the member
functions of that class. The main() cannot contain statements that access number and cost
directly. The following is the format for calling a member functions.
Object_name.function_name (actual-arguments);
For example the function call statement
x.getdata( 100,75.5);
is an valid and assigns the value 100 to number and 75.5 to cost of the object x by
implementing the getdata( ) function. The assignments occur in the actual functions.
Similarly,
x.putdata();
would display the values of data members. Remember, a member function can be invoked
only by using an object(of the same class).
The statements like,
getdata(100,75.5); //has no meaning
x.number=100; // illegal
The variables declared as public can be accessed by the objects directly.
Eg:Class xyz
{
int x;
int y;
public:
int z;

14
..........
..........
}
void main( )
{
..........
.........
xyz p; //creating an object of class xyz
p.x = 0; // error, x is private
p.z = 10 //ok z is public
..........
..........
}
Examples:
1. Class: person
Object: girl, boy
Attributes: Name, Age
Operations: speak( ), listen( ), walk( )
2. Class: vehicle
Object: car, bus
Attributes: Name, model, color
Operations: start( ),stop( ),accelerate( )

In C++ class can be represented as:


Class account
{
Private:
char name[20];
int act_type;
float balance;
Public:
deposit( );
withdraw( );
};
It is similar to structure declaration in C.
It enables the creation of class variables called objects.
Example: account saving; account current;
Example programs:
1./*To find whether given number is even or odd using Class*/

15
#include<iostream.h>
#include<conio.h>
class even
{
private:
int a;
public:
void getdata()
{
cout<<”\nenter the number to check: ”;
cin>>a;
}
void check()
{
if(a%2==0)
cout<<”\ngiven number is even”;
else
cout<<”\ngiven number is odd”;
}
};
void main()
{
clrscr();
even e;
e.getdata();
e.check();
getch();
}.
Output:
Enter the number to check: 9
Given number is odd

2./*To calculate velocity by using the formula v=u+(a*t) */


#include<iostream.h>
#include<conio.h>
class velocity
{
int v,u,a,t;
public:
void getdata( )
{
cout<<"Enter the values for initial velocity, acceleration and time\n";
cin>>u>>a>>t;
}
void calculate( )
{v=u+(a*t);

16
cout<<"FINAL VELOCITY= "<<v<<endl;
}
};
void main( )
{
clrscr( );
velocity ob;
ob.getdata( );
ob.calculate( );
getch( );
}
Data hiding:
Data is hidden inside a class, so that it cannot be accessed by mistake by any function
outside the class, which is a key feature of OOP.
C++ imposes a restriction to access both the data and functions of a class. It is achieved by
declaring the data part as private. All the data and functions defined in a class are private by
default. But for the sake of clarity, the members are declared explicitly as private. Normally,
data members are declared private and member functions are declared public
Class member accessibility
Access specifiers in OOP’s:
Private
Protected
Public

Private members
The private members of a class have strict access control. only the member functions of the
same class can access these members. The private members of a class are inaccessible
outside the class, thus providing a mechanism for preventing accidental modification of the
data members.
Example:
class person
{
private: //access specifier
...........
.int age;
int getage( );
...........
};
person p1;
a=p1.age( ); //cannot access private data
p1.getage( ); //cannot access private function

17
Protected members
The access control of the protected members is similar to that of private members and has
more significance in inheritance.
Example:
class person
{
protected: //access specifier
............
int age;
int getage( );
...........
};
person p1;
a=p1.age( ); //cannot access protected data
p1.getage( ); //cannot access protected function (same as private)

Public members
The members of a class which are to be visible (accessible) outside the class, should be
decalred in public section. All data members and function declared in the public section of
the class can be accessed without any restriction from anywhere in the program.
Example:
class person
{ public: //access specifier
............
int age;
int getage( );
...........
};
person p1;
a=p1.age( ); //can access public data
p1.getage( ); //can access public function
Table.4.2 Access Specifier of C++ Program

18
Data Encapsulation
• Encapsulation is the most basic concept of OOP.
• The wrapping up of data and functions into a single unit(called class) is known as
encapsulation.
• Data encapsulation is the most striking feature of a class.
• It is a mechanism that associates the code and the data it manipulates and keeps them
safe from any external interface and misuse.
• The data is not accessible to the outside world (entire program), and only those
functions which are wrapped in the class can access it.
• These functions provide the interface between the object’s data and the program.
• This is also known as “data hiding” or “information hiding”.
Data Abstraction
Abstraction refers to the act of representing essential features without including the
background details or explanations.
To understand this concept more clearly, take an example of 'switchboard'.
You only press particular switches as per your requirement. You need know the internal
working of these switches.
What is happening inside is hidden from you. This is abstraction, where you only know
the essential things to operate on switch board without knowing the background details of
switch board.
• Classes use the concept of abstraction.
• Since the classes use the concept of abstraction, they are also known as Abstract
Data Types (ADT).
Inheritance
• It is the process by which objects of one class acquire the properties of objects of
another class.
• It provides reusability i.e., we can add additional features to an existing class
without modifying it.
• It is the capability to define a new class in terms of an existing class.
• This is possible by deriving a new class from the existing one.
• An existing class is known as a base class and the new class is known as derived
class.
Consider an example,

When the class child inherits the class parent - the class child is referred to as derived
class (sub-class), class parent is referred to as base class (super class).

19
Fig.4.10. Inheritance
• Child has two parts:
➢ a derived part and
➢ Incremental part (new code written specifically for child class).
• Child has its own properties, in addition to those acquired from its parent.

Fig.4.11. Example for Inheritance


Inheritance
The mechanism of deriving a new class from an old one is called inheritance (or derivation).
The old class is referred to as the base class and the new one is called the derived class. The
derived class with only one base class is called single inheritance and one with several base
classes is called multiple inheritance. On the other hand, the traits of one class may be
inherited by more than one class. This process is known as hierarchical inheritance. The
mechanism of deriving a class from another ‘derived class’ is known as multilevel
inheritance. The following figure shows various forms of inheritance that could be used for
writing extensible programs. The direction of arrow indicates the direction of inheritance.
Definition:
The mechanism of deriving the new class from an old one is called inheritance. The old class
is called as base class and the new class is called as derived class.

20
Types of Inheritance:
• Single inheritance
• Multiple inheritance
• Multilevel inheritance
• Hierarchical inheritance(refer Assignment)
• Hybrid inheritance
Defining derived classes:-A derived class is defined by specifying its relationship with the
base class in addition to its own details. The general form:-
class derived-class-name: visibly-mode base-class-name
{
------------//
------------//
members of derived class
------------
};
The colon indicates that the derived-class-name is derived from the base-class-name. The
visibility mode is optional and, if present, may be either private or public. The default
visibility-mode is private. Visibility mode specifies whether the features of the base class
are privately derived or publicly derived.
Single Inheritance:-

Fig.4.12. Single Inheritance


The new class can be derived from only one base class is called single inheritance.
Let us consider a simple example to illustrate inheritance. The following program shows the
base class B and a derived class D. The class B contains one private data member, one public
data member, and three public member functions. The class D contains one private data
member and two public member functions.
#include<iostream.h>
class B
{

21
int a; //private; not inheritable
public:
int b; //public; ready for inheritance
void get_ab()
{
a=5;
b=10;
}
int get_a(void).
{.
return a;
}
void show_a(void)
{
cout<<”a=”<<a<<endl;
}
};
class D:public B//public derivation
{
Int c;
public:
void mul(void)
{
c=b*get_ab();
}
Void display()
{
cout<<”a=”<<get_ab()<<endl;
cout<<”b=”<<b<<endl;
cout<<”c=”<<c<<endl;

22
}
};
void main()
{D d;
d.get_ab();
d.mul();
d.show_a();
d.display();
d.b=20;d.mul();
d.display();
}
Output:-
a=5
a=5
b=10
c=50
a=5
b=20
c=100
The class D is a public derivation of the class B. Therefore, D inherits all the public members
of B and retains their visibility. Thus a public member of the base class B is also a public
member of the derived class D. The private members of B cannot be inherited by D. The
program illustrates that the objects of class D have access to all the public members of B. Let
us have a look at the functions show_a() and mul().
void show_a()
{
cout<<”a=”<<a<<endl;
}
void mul()
{
c=b*get_a();//c=b*a

23
Although the data member a is private in B and cannot be inherited, objects of D are able to
access it through an inherited member function of B. Let us now consider the case of private
derivation.
#include<iostream.h>
class B
{
int a;
public:
int b;
void get_ab();
int get_a(void);
void show_a(void);
};
class D:private B
{
int c;
public:
void mul(void);
void display();
};
In private derivation, the public members of the base class become private members of
derived class. Therefore, the objects of D cannot have direct access to the public member
functions of B. The statement such as d.get_ab(), d.get_a(), d.show_a() will not work.
Program:
-#include<iostream.h>class B
{
int a;//private; not inheritable
public:
int b;//public; ready for inheritance
void get_ab()
{
a=5;

24
b=10;
}
int get_a(void)
{
return a;
}
void show_a(void)
{
cout<<”a=”<<a<<endl;
}
};
class D:private B//private derivation
{
int c;
public:
void mul(void)
{
c=b*get_ab();
}
Void display()
{
cout<<”a=”<<get_ab()<<endl;
cout<<”b=”<<b<<endl;
cout<<”c=”<<c<<endl;
}
};
void main()
{
D d;
/d.get_ab(); it won’t work

25
d.mul();
//d.show_a(); won’t work
d.display();
//d.b=20; won’t work
d.mul(); d.display();
}
Output:-
a=5
b=10
c=50
a=12
b=20
c=240
Multilevel Inheritance:-
The class A serves as a base class for the derived class B which in turn serves as a base class
for the derived class C. The chain ABC is known as inheritance path.

Fig.4.13. Multilevel Inheritance

Fig.4.14. Inheritance Path

26
A derived class with multilevel inheritance is declared as follows.
class A(....) ;
class B:public A(.....);
class C:public B(.....);
The multilevel inheritance is defined as, the new class is derived from another derived class.
Here the class A serves as a base class for the derived class B which in turn serves as a base
class for the derived class C. The derived class is defined as,
Class A
{
//body of base class A
};
Class B : public A
{
//body of intermediate base class B
};
Class C : public B
{
//body of derived class
};
Example Program
EXAMPLE :1
#include <iostream.h>
class student
{
protected:
int rollno:
public:
void getroll(int x)
{
rollno = x;
}

27
};
void test: public student
{
protected:
float sub1, sub2;
public:
void getmart(int y, int z)
{
sub1 = y; sub2= z;
}
};
void result : public test
{
float total;
public:
void display( )
total =sub1 + sub2;
cout<<rollno<<sub1<<sub2;
cout<<total;
}
};
void main( )
{
result s;
s.getroll(101);
s.getmark(90, 100);
s.display( );
}
EXAMPLE :2
#include<iostream.h>

28
class student
{
protected:
int roll_number;
public:
void get_number(int);
{
roll_number=a;
}
void put_number(void)
{
cout<<”Roll Number:”<<roll_number<<endl;
}
};
class test: public student//First level derivation
{
protected:
float sub1;
float sub2;
public:
void get_marks(float,float)
{
sub1=x;
sub2=y;
}
void put_marks(void)
{
cout<<”Marks in sub1=”<<sub1<<endl;
cout<<”Marks in sub2=”<<sub2<<endl;}
};

29
class result : public test // second level derivation
{
float total;
public:
void display(void)
{
total=sub1+sub2;
put_number();
put_marks();
cout<<”Total=”<<total<<”\n”;
}
};
void main()
{
result student1;
student1.get_number(111);
student1.get_marks(75.0,59.5);
student1.display();
}
Output:-
Roll Number:111
Marks in sub1:75
Marks in sub2:59.5
Total:134.5
Multiple Inheritance:-
A class can inherit the attributes or properties of two or more classes that is a new class can
be derived from more than one base class is called multiple inheritance. Here the class A ,
class B and class C serves as a base class for the derived class D

30
Fig.4.15. Multiple Inheritance
The derived class definition syntax is:
class d: visibility base-1,
visibility base 2,...
{
body of class D;
};
Example:#include<iostream.h>
class A
{
protected:
int rollno;
public:
void getroll(int x)
{
rollno=x;
}
};
class B
protected:
int sub1,sub2;
public:
void getmark(int y,int z)\
{

31
sub1=y;
sub2=z;
}
};
class C : public A, public B
{
int total;
public:
void display()
{
total=sub1+sub2;
cout<<”roll no:”<<rollno<<”sub1:”<<sub1<<”sub2:”<<sub2;
cout<<”total”<<total;
}
};
void main()
{
C s;
s.getroll(435);
s.getmark(100,90);
s.display();
}
Run:
Roll no : 435
Sub1: 100
Sub2: 90

32
Hierarchical Inheritance:-

Fig.4.16. Hierarchical Inheritance


The hierarchical inheritance structure is given below .This type is helpful when we have class
hierarchies. In this scheme the base class will include all the features that are common to the
subclasses.
#include<iostream.h>
#include<string.h>
class A
{
protected:
int x, y;
public:void get ( )
{
cout<<”Enter two values”<<endl;
cin>> x>>y;
}
};
class B : public A
{
private:
int m;
public:
void add( )
{
m= x + y;cout<<”The Sum is “<<m;

33
}
};
class C : public A
{
private:
int n;
public:
void mul( )
{
n= x * y;
cout << “The Product is “<<n;
}
};
class D : public A
{
private:
floatl;
public:
void division( )
{
l = x / y;
cout <<”The Quotient is “<< l;
}
};
void main( )
{
Bobj1;
Cobj2;
Dobj3;
B.get( );

34
B.add( );
C.get( );
C.mul( );
D .get( );
D .division( );
}
Output of the Program
Enter two values12 6
The Sum is 18
The Product is 72
The Quotient is 2.0
Hybrid Inheritance:
Hybrid inheritance = multiple inheritance + multi-level inheritance
The hybrid inheritance is defined as a combination of multilevel and multiple inheritances.
This new class can be derived by either multilevel or multiple method or both.

Fig.4.17. Hybrid Inheritance


Example program In this program the derived class (result) object will be inheriting the
properties of both test class and sports class.
#include <iostream.h>
class student
{
protected:
int rollno;
public:

35
void getroll (int x)
{
rollno = x;
}
};
class test: public student
{
protected:
int sub1, sub2;
public:
void getmark (int y, int z)
{
sub1 = y;
sub2 = z;
}
};
Class sports
{
protected:
int score;
public:
voidgetscore (int a )
{
score=a;
}
};
class result: public test, public sports
{
int total;
public:

36
void display()
{
total= sub1+sub2+score;
cout<<”rollno:”<<rollno<< “total:”<<”Score:”<<total;
}
};
void main( )
{
result S;
s.getroll(101);
s.getmark(90,98);
s.getscore(2000);
s. display( );
}
Run:
Rollno: 101
Total: 188
Score: 2000
Polymorphism
Polymorphism is a key to the power of OOPs.
• It is a Greek word, means the ability to take more than one form (manyforms).
• It is the concept that supports the capability of data to be processed in more than one
form i.e., It allows a single name to be used for more than one related purpose, which
are technically different.
• For example, an operation may exhibit different behaviour in different instances.
• The behaviour depends upon the types of data used in the operation.

The following are the different ways of achieving polymorphism in a C++program:


➢ Function overloading
➢ Operator overloading
➢ Dynamic binding

37
Fig.4.13. Example for polymorphism
The above fig illustrates that a single function name can be used to handle different number
and different types of arguments. This is similar to a particular word having several different
meanings depending on the context. Using a single function name to perform different types
of tasks is known as function overloading.
Let us consider the operation of addition.
➢ For two numbers, the operation will generate a sum.
➢ If the operands are strings then the operation would produce a third string by
concatenation. This is known as operator overloading.
Function Overloading:
We can use the same function name to create functions that perform a variety of different
tasks. This is known as function polymorphism in oop. Using the concept of function
overloading, we can design a family of functions with one function name but with
different argument lists. The function would perform different operations depending on
the argument list in the function call. The correct function to be invoked is determined by
checking the number and type of the arguments but not on the function type.
Example:-
Declarations:-
1. int add (int a, int b);
2. int add (int a, int b, int c);
3. double add (double x, double y);
4. double add (int p, double q);
5. double add (double p, int q);
Function calls:-
cout << add (0.75, 5);// uses 5
cout << add (5, 10);// 1
cout << add (15, 10.0); // 4 cout << add (12.5, 7.5); // 3 cout << add (5, 10.15); //2

38
#include<iostream.h>
class funoverloading
{
int a, b, c;
public:
void add ( )
{
cin>>a>>b;
c = a + b;
cout << c;
}
int add (int a, int b);
{
c = a + b;
return c;
}
void add (int a)
{
cin>>b;
c = a + b;
cout<<c;
}
}
}
void main ( )
{
funoverloading F; int x;
F. add ( );
x = F. add (10, 5);
cout<<x;

39
F. add (5);
}
Output:-
53
c=8
c = 15
5
c = 10

Operator Overloading:
C ++ has the ability to provide the operators with a special meaning for a data type. The
mechanism of giving such special meanings to an operator is known as operator
overloading.
The process of overloading involves the following steps:
• Create a class that defines the data type that is to be used in the overloading
operation.
• Declare the operator function operator op()in the public part of the class.
• It may be either a member function or a friend function.
• Define the operator function to implement the required operations.
Syntax:-
returntype classname:: operator op (argument list)
{
Function body
}
Example:-
void space:: operator-( )
{
x=-x;
}
Overloading Unary Operators:-
Let us consider the unary minus operator. A minus operator when used as a unary take just
one operand. We know that this operator changes the sign of an operand when applied to a
basic data item. We will see here how to overload this operator so that it can be applied to an
object in much the same way as is applied to an int or float variable. The unary minus when
applied to an object should change the sign of each of its data items.

40
#include<iostream.h>
{
int x;
int y;
int z;
public:
void getdata(int a, int b, int c); void display(void);
void operator-(); //overload unary minus
};
void space::getdata(int a, int b, int c)
{
x=a;
y=b;
z=c;
}
void space::display(void)
{
cout<<x<<” ”; cout<<y<<” “; cout<<z<<” “;
}
void space::operator-()
{
x=-x;y=-y;z=-z;
}
int main()
{
space S; S.getdata(10,-20,30);cout<<”S=”; S.display();
- S; cout<<”S=”; S.display(); return 0;
}
Output:-
S= 10 -20 30

41
S= -10 20 -30
Note:
The function operator-() takes no argument. Then, what does this operator function do? It
changes the sign of data members of the object S. Since this function is a member function of
the same class, it can directly access the members of the object which activated it.
Overloading Binary Operators:-
The same mechanism which is used in overloading unary operator can be used to overload a
binary operator.
# include<iostream.h> class complex
{
float x; float y; public:
complex()
{
}
complex(float real, float imag)
{
x=real;
y=imag;
}
complex operator+(complex); void display(void);
};
complex complex::operator+(complex c)
{
complex temp; temp.x=x+c.x; temp.y=y+c.x; return(temp);
}
void complex::display(void)
{
cout<<x<<”j”<<y<<”\n”;
}
int main()
{

42
complex C1,C2,C3; C1=complex(2.5,3.5) C2=complex(1.6,2.7) C3= C1 + C2; cout<<”C1 =
”;
C1.display(); cout<<”C2 = ”; C2.display(); cout<<”C3 = ”; C3.display();
return 0;
}
Output:-
C1=2.5 +j3.5
C2=1.6 + j2.7
C3= 4.1 +j6.2
Dynamic binding
➢ Binding refers to the linking of a procedure call to the code to be executed in response
to the call.
➢ Dynamic binding (also known as late binding) means that the code associated with a
given procedure is not known until the time of the call at run-time.
➢ It is associated with polymorphism and inheritance.
Example:
➢ Consider the procedure “draw” in the above fig. By inheritance every object will have
this procedure.
➢ Its algorithm is however, unique to each object and so the draw procedure will be
redefined in each class that defines the object.
➢ At run-time, the code matching the object under current reference will be called.
Message passing
An OO program consists of a set of objects that communicate with each other.
The process of programming in an OO language, therefore involves the following steps:
• Creating classes that define objects and their behaviour.
• Creating objects from class definitions and
• Establishing communication among objects.
• A message for an object is a request for execution of a procedure and therefore will
invoke a function (procedure) in the receiving object that generates the desired result.
• Objects communicate with one another by sending and receiving information much
the same way as people pass messages to one another.
• Message passing involves specifying the name of the objects, the name of the
function (message) and the information to be sent.
Virtual Function
When we use the same function name in base and derived classes, the function in the base
classes is declared as virtual using keyword ‘virtual’ preceding its normal declaration.

43
The member function that can be changed at runtime is called virtual function.
Class classname
{
public:
.....
virtual returntype functionname (arguments)
{
.....
. . . . .}};
The virtual function should be defined in the public section of a class. When one function is
made virtual and another one is normal, and compiler determines which function to call at
runtime. In this we have to create a ‘basepointeer’. If the basepointer paints to a base class
object means it will execute the base class function.
If the basepointer points to a derived class object means it will execute the derived class
function.
Example Program:
#include <iostream.h>
Class A
{
public:
void displayA( )
{
cout<<”Welcome”;
}
virtual void show( )
{
cout<<”Hello”;
}
};
class B: public A
{
public:

44
void display( )
{
cout<<”Good Morning”;
}
void show( )
{
cout<<”Hai”;
}
};
void main( )
{
A S1;
B S2;
A *bptr;
bptr = &S1;
bptr→show( ); //Calls base class show
bptr=&S2( );
bptr→show( );
S2. displayA( );
S2.display( );
//Calls derived class show
//Calls base class displayA
//Calls derived class display
}
RUN:
Hello
Hai
Welcome
Good Morning

45
Explanation:
The base pointer first holds the address of the base class object means it will run the base
class member function display and show will be executed. Next the base pointer points to the
derived class object, in this before executing the derived class function if will check whether
the corresponding base class function is ‘virtual’ or not, if it is not virtual then execute the
base class function otherwise it will execute the derived class function.

Rules for virtual function:


1. Virtual function must be a member of some class.
2. They cannot be static members.
3. They are accessed by using base pointer.
4. A virtual function in a base class must be defined eventhough it may not be used.
5. A prototype (or declaration) of a base class virtual function and all the derived class
version must be identical.
6. We cannot we a pointer to a derived class to access an object of the base class.
The duplication of inherited members due to the multiple paths can be avoided by making the
common base class as virtual base class while declaring the direct or intermediate base
classes as shown below.
class A
{
------
------
};
class B1:virtual public A
{
-----
-----
};
class B2:public virtual A
{
-----
-----
};

46
class C:public B1,public B2
{
-----
-----
};
When a class is made a virtual base class, C++ takes necessary care to see that only one copy
of that class is inherited, regardless of how many inheritance paths exist between the virtual
base class and a derived class.
class A
{
private:
int a;
public:
void funcA()
{
cin>>a;
cout<<”a=”<<a;
}
};
class B:virtual public A
{
private:
int b;
public:
void funcB()
{
cin>>b;
cout<<”b=”>>b;
}};
class C:public virtual A
{

47
private:
int c;
public:
void funC()
{
cin>>c;
cout<<”c=”>>c;
}
};
class D : public B, public C
{
private:
int d;
public: void funD()
{
cin>>d;
cout<<”d=”>>d;
}
};
void main()
{ d1; C c1; c1.funC(); d1.funA();
d1.funB();
d1.funC();
d1.funD();
}
Output:-
5
c=5
4
a=4
6

48
b=6
8
c=8
9
d=9
Text / Reference Books:

49

You might also like