2-1 OOP-Through C++ R19
2-1 OOP-Through C++ R19
2-1 OOP-Through C++ R19
Regulations R-19
UNIT-1
[INTRODUCTION TO C++]
Syllabus:
Difference between C and C++, Evolution of C++, The Object Oriented Technology,
Disadvantage of Conventional Programming-, Key Concepts of Object Oriented Programming,
Advantage of OOP, Object Oriented Language.
Introduction:
Main program
Data Data
Communication
Functions Functions
Object C
Functions
Data
Structure of C Program
Collection of functions
Void main() Entry point
{
call the functions from here
}
II B.Tech-CSE-I OOP THROUGH C++ : UNIT-1
Sem
Structure of C++ Program
class Example
{
Collection of functions and variables
};
Void main() Entry point
{
create the object of the class
using the object invoke the functions in the class
}
1. class : It is a user defined data type, which consists of both data and functions into a
single unit.
In OOP data must be represented in the form of a class . A class contains variables for
storing data and functions to specify various operations that can be performed and hence
it is only logical representation of data and not physical representation.
so class is collection of Data members and Member functions.
class is a blue print of an object.
Once a class has been defined we can create any number of objects.
Each object is associated with the data of type class which they were created.
class provides the concept of Encapsulation.
class provides the concept of Data hiding with private declarations.
Declaration of C++ class :
A class is collection of Data members and member functions which hide from other
programs.
The key word 'class' is used to declare a class. Inside the class access specifiers are used
to declare variables and methods.
II B.Tech-CSE-I OOP THROUGH C++ : UNIT-1
Sem
Creating a class : To create class use the keyword class that has the following syntax :
[access specifier] class < class name >
{
Access specifier :
variable declarations;
Access specifier :
method declarations & implementations
};
Example program :
#include<iostream>
using namespace std;
class temp
{ To access the members we have to create object .
int a;
NOTE: In c++ the private data should be accessed only
public : by member functions of the same class.
void read() Member functions : The functions which are declared
{ inside the class are called as member functions.
a=100; Default access specifier in C++ is private.
cout<<a; so here 'a' is a private member .
} private members are not directly accessible from out
}; side the class. (this is called data hiding it is achieved
int main() with private declarations.)
{ main() is out side the class so 'a' is not accessible with
temp obj; object from main
//obj.a=10; obj.a =10 is an invalid statement.
obj.read();
return 0;
}
2. Object :
A class is only logical representation of data. Hence to work with the data represented by
the class you must create a variable for the class which is called as an object.
So object is a variable of type class.
Object is the basic unit of object-oriented programming.
In a class to access data members first memory have to be allocated.
No memory is allocated when a class is created.
Memory is allocated only when an object is created, i.e., when an instance of a class is
created. Object is physical copy and class is logical copy.
Syntax for creating an object :
class name followed by variable name
Objects are identified by its unique name.
An object represents a particular instance of a class.
II B.Tech-CSE-I OOP THROUGH C++ : UNIT-1
Sem
There can be more than one instance of an object.
Each instance of an object can hold its own relevant data.
An Object is a collection of data members and associated member functions also known
as methods. Characteristics of an object are represented in a class as Properties.
The actions that can be performed by objects becomes functions of the class and is
referred to as Methods.
For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR
represents individual Objects. In this context each Car Object will have its own, Model,
Year of Manufacture, Colour, Top Speed, Engine Power etc., which form Properties of the
Car class and the associated actions i.e., object functions like Start, Move, Stop form the
Methods of Car Class.
3. Data Encapsulation : A class can contain variables for storing data and functions to
specify various operations that can be performed on data. This process of wrapping up
of data and functions that operate on data as a single unit is called as Encapsulation.
When using Data Encapsulation, data is not accessed directly, it is only accessible
through the functions present inside the class. Data Encapsulation enables the
important concept of data hiding possible.
4. Data Abstraction : Abstraction refers to the act of representing essential features
without including the back ground details or explanations. It represents a functionality
of a program without knowing implementation details. It is an approach that speaks
about hiding of the complexity and consume only the functionality.
5. Inheritance: Creating a new class from an existing class or base class is called
Inheritance. The base class is also known as parent class or super class, The new class
that is formed is called derived class. Derived class is also known as a child class or sub
class. Inheritance helps in reducing the overall code size of the program, which is an
important concept in object-oriented programming.
The concept of inheritance provides the idea of reusablity. Instead of rewritting the
code you can create the class from the existing class and extending the functionality of
existing class. This mean that we can add additional features to an existing class with
out modifying it. This is possible by designing a new class that will have the combined
features of both the classes.
6. Polymorphism : Polymorphism comes from the Greek words “poly” and “morphism”.
“poly” means many and “morphism” means form i.e.. many forms.
Polymorphism means the ability to take more than one form. Advantage of this is you
can make an object behave differently in different situations, so that no need to create
different objects for different situations.
Polymorphism can be achieved with the help of Overloading and Overriding concepts
and it is classified into compile time polymorphism and Runtime polymorphism.
II B.Tech-CSE-I OOP THROUGH C++ : UNIT-1
Sem
Function with same name but different arguments .
Functioning is different.
Example : add(int a, int b) add(int a, int b, int c)
add(float a, float b) add(float a, float b, float c)
Applications Of C++ :
UNIT II
[Classes and Objects & Constructors and Destructor]
Classes and Objects &Constructors and Destructor: Classes in C++-Declaring Objects, Access
Specifiers and their Scope, Defining Member Function-Overloading Member Function, Nested
class, Constructors and Destructors, Introduction, Constructors and Destructor- Characteristics
of Constructor and Destructor, Application with Constructor, Constructor with Arguments
(parameterized Constructor, Destructors- Anonymous Objects.
STRUCTURE IN C
In C , it is possible to combine dissimilar data types using structure but it has the following
limitations :
a) Functions are not allowed as members of structure.
b) By default all the structure members are public and direct access to data members is
possible. Hence , security to data or data hiding is not provided.
c) The struct data type is not treated as built -in type , that is the use of struct keyword is
necessary to declare objects.
d) The data members cannot be initialized inside the structure.
Write a program to access data members of a structure.(Using dot(.) operator for simple
variable)
#include<stdio.h>
#include<conio.h>
struct student {
int sid;
char sname[20];
float avg;
};
void main() {
struct student s1 = {1901,"RAMA",72.8};
printf("\n s1 details With simple variable");
printf("\n Student id = %d", s1.sid);
printf("\n Student Name= %s", s1.sname);
printf("\n Student average = %f", s1.avg);
}
Write a program to access data members of a structure.(Using arrow(->) operator for pointer
variable)
#include<stdio.h>
#include<conio.h>
struct student {
int sid;
char sname[20];
float avg;
}*s2;
void main() {
struct student s = {1902,"KAMALA",82.6};
s2=&s;
printf("\n s2 details With pointer variable");
printf("\n Student id = %d", s2->sid);
printf("\n Student Name= %s", s2->sname);
printf("\n Student average = %f", s2->avg);
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
Creating a class : To create class use the keyword class that has the following syntax :
[access specifier] class < name of class >
{
private :
declaration of variables;
declaration of functions;
public :
declaration of variables;
declaration of functions;
};
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
example:
class student {
private:
int sid;
char sname[20];
float avg;
void readvalues();
public :
void printvalues();
};
The declaration of a class is enclosed with curly braces and terminated with a semicolon.
The class body contains declarations of variables and functions and these are called
members of class.
The key words private and public are known as labels that are followed by colon(:).
The class members that have been declared as private can be accessed only with in the class.
The class members that have been declared as public can be accessed outside the class also.
#include<iostream>
using namespace std;
class student
{
//private:
int sid;
char sname[20];
public:
void getdata()
{
cout<<"Enter STUDENT ID : ";
cin>>rollno;
cout<<"Enter STUDENT NAME : ";
cin>>sname;
}
void putdata()
{
cout<<"\n Student ID : "<<sid;
cout<<"\n student Name : "<<sname;
}
};
int main()
{
student s;
s.getdata();
s.putdata();
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
Declaring objects :
The declaration of object is same as declaration of variables of basic data types.
Defining objects of class data type is known as class instantiation.
Memory is allocated only when objects are created.
syntax :
class_name variable_name;
Ex: student s;
Example:
a) int x, y, z; // declaration of integer variables
x, y, z are variables of type integer.
b) char a, b, c; //declaration of character variables
a, b, c are variables of type character.
c) student s1,s2, *s3; // declaration of object or class type variables
s1, s2, s3 are three objects of class student . *s3 is a pointer to class student.
s3 -> sid
where s3 is a pointer and sid is a data member .
The arrow(->) operator is used because s3 is a pointer.
• if data member is declared as public, we can access the data member by using object .
• If data member is declared private then it is not accessible with object.
Access specifiers :
Access specifiers are used to identify access rights for the data and member
functions of the class. There are three main types of access specifiers in C++
programming language:
- public
- private
- protected
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
public :Public members are accessible from outside the class. The keyword public is
used to allow objects to access the member variables of a class directly.
The member variables and functions declared as public can be accessed directly by
the object.
Write a program to declare all members of a class as public. Access the elements using object.
#include<iostream>
using namespace std;
class item {
public: // public section begins
int codeno;
float price;
int qty;
}; // end of class
int main() {
item one; // object declaration
one.codeno=123; // member initialization
one.price=123.45;
one.qty=150;
cout<<"\n Codeno = "<<one.codeno;
cout<<"\n Price = "<<one.price;
cout<<"\n Quantity = "<<one.qty;
return 0;
}
private :
A private member within a class denotes that only members of the same class have
accessibility. The private member is inaccessible from outside the class.
To prevent member variables and functions from direct access the private keyword is used.
#include<iostream>
using namespace std;
class item {
private: // private section begins
int codeno;
float price;
int qty;
}; // end of class
int main() {
item one; // object declaration
one.codeno=123; // member initialization
one.price=123.45;
one.qty=150;
cout<<"\n Codeno = "<<one.codeno;
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
when the above program is compiled, the compiler will display the error message
codeno, price, qty are private in this scope.
so, the private members are not accessible by the object directly.
Now how to access the private members.
To access private data members a member function must be declared in the class in public
section.
** Member functions are used to initialize the data members.
#include<iostream>
using namespace std;
class item {
private: // private section begins
int codeno;
float price;
int qty;
public : // public section starts
void display(){ // member function
codeno=123; // member initialization
price=123.45;
qty=150;
cout<<"\n Codeno = "<<codeno;
cout<<"\n Price = "<<price;
cout<<"\n Quantity = "<<qty;
}
}; // end of class
int main() {
item one; // object declaration
one.display();
return 0;
}
protected: A protected access specifier is a stage between private and public access. If
member functions defined in a class are protected, they cannot be accessed from outside
the class but can be accessed from the derived class.
We can not access protected section members from outside the class by any object.
protected keyword is used in inheritance concepts.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
Private ×
Public
Explanation : In the above program display() is the member function defined inside the
class in public section. We know that object has permission to access the public members of
the class. Under main() function object e1 is declared. The public member function can
access the private members of the same class. The function display() initializes the private
member variables and display the contents on the console.
Write a program to declare private member function and access it using public member
function.
#include<iostream>
using namespace std;
class employee {
private: //private section starts
int eno;
char ename[20];
float esal;
void readvalues() { //private member function
cout<<"Enter Emp No : ";
cin>>eno;
cout<<"Enter Emp Name : ";
cin>>ename;
cout<<"Enter Emp sal : ";
cin>>esal;
}
public: //public section starts
void display() { //public member function
readvalues(); //call to private member function
cout<<"\n Employee Number : "<<eno;
cout<<"\n Employee Name : "<<ename;
cout<<"\n Employee salary : "<<esal;
}
};
int main() {
employee e1; // object declaration
//e1.readvalues(); //not accessible
e1.display(); // call to public member function
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
public:
void display(); // prototype declaration
};
void employee :: display() // definition outside the class
{
cout<<"Enter Emp No : ";
cin>>eno;
cout<<"Enter Emp Name : ";
cin>>ename;
cout<<"Enter Emp sal : ";
cin>>esal;
cout<<"\n Employee Number : "<<eno;
cout<<"\n Employee Name : "<<ename;
cout<<"\n Employee salary : "<<esal;
}
int main() {
employee e1; // object declaration
e1.display(); // call to public member function
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
// to demonostrate invoking of member functions inside and out side the class
#include<iostream>
using namespace std;
class employee
{
private:
int eno;
char ename[20];
float esal;
public:
void readvalues() {
cout<<"Enter Emp No : ";
cin>>eno;
cout<<"Enter Emp Name : ";
cin>>ename;
cout<<"Enter Emp sal : ";
cin>>esal;
}
void display();
};
void employee :: display() {
cout<<"\n Employee Number : "<<eno;
cout<<"\n Employee Name : "<<ename;
cout<<"\n Employee salary : "<<esal;
}
int main() {
employee e1;
e1.readvalues();
e1.display();
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
Overloading is nothing but two or more functions is defined with same name but different
parameters
Function overloading can be considered as an example of polymorphism feature in C++.
Function overloading is a compile-time polymorphism.
Rules for Function overloading :
An overloaded function must have :
Different type of parameters
ex: void test(int a); void test(float a);
Different number of parameters
ex: void test(); void test(int a);
Different sequence of parameters
ex: void test(int a , float b); void tes t(float a , int b);
#include<iostream>
using namespace std;
class addition {
public:
int add(int a, int b);
int add(int a, int b,int c);
double add(int a, double b);
double add(double a , int b);
};
int addition::add(int a, int b) {
cout<<"Function 1"<<endl;
return (a+b);
}
int addition::add(int a, int b, int c) {
cout<<"Function 2"<<endl;
return (a+b+c);
}
double addition::add(int a, double b) {
cout<<"Function 3"<<endl;
return (a+b);
}
double addition::add(double a,int b) {
cout<<"Function 4"<<endl;
return (a+b);
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
int main() {
addition obj;
cout<<"Addition of two integers : "<<obj.add(1,2)<<endl;
cout<< "Addition of three integers : "<<obj.add(3,4,5)<<endl;
cout<<"Addition of integer and double : "<<obj.add(4,5.6)<<endl;
cout<<"Addition of double and integer : "<<obj.add(7.4,5)<<endl;
return 0;
}
Nested class
A nested class is a class that is declared in another class.
The outside class is called enclosing class and inside class is called nested class.
The nested class is also a member variable of the enclosing class and has the same access
rights as the other members.
The member functions of the enclosing class have no special access to the members of a
nested class.
Example :
#include<iostream>
using namespace std;
class A {
public:
class B { // Member variable of class A
private:
int a,b;
public:
void getdata() { // Member function of class B
cout<<"Enter values for a & b : ";
cin>>a>>b;
}
void putdata() {
cout<<"a ="<<a<<endl<<"b ="<<b;
}
};
};
int main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata();
obj.putdata();
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
Characteristics of constructors :
1. Constructor name and class name should be same.
2. Constructors should be declared in public section.
3. Constructors never have any return value (or) data type including void.
4. The main function of Constructor is to initialize objects and allocate appropriate
memory to objects.
5. Constructors can have default values and can be overloaded.
6. Constructor may or may not have arguments (or) parameters.
7. Constructor is executed only once when the object is created.
8. Constructors are automatically invoked they are not invoked with dot(.) operator.
9. Constructor is invoked automatically when object of class is created.
Constructors can be defined either inside the class definition or outside class definition using
class name and scope resolution :: operator.
class A {
public:
int i;
A(); // constructor declared
};
A::A() // constructor definition
{
i = 1;
}
Page 14
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
main() {
class num x;
}
In the above example, class num has three integer variables a, b, and c
In definition, the member variables of a class num are initialized to zero.
When an object is created, its member variables(private and public) are automatically
initialized to the given value. By this we understood that with out calling a member
function explicitly to initialize member variables The compiler automatically calls the
constructor when an object is created and member variables are initialized.
The compiler automatically calls the constructors.
In case there is no constructor in the program, the compiler calls a dummy constructor.
Write a program to define a constructor and initialize the class data member variables with
constants.
#include<iostream>
using namespace std;
class num {
private:
int a,b,c;
public:
int x;
num(void); //declaration of constructor
void show()
{
cout<<"\n x = " <<x<<" a= "<<a<< " b= "<<b<<" c= "<<c;
}
};
Page 15
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
1. Default Constructor :
Constructor with out arguments are called Default Constructor.
There are two types Default Constructors
One is System written which is created by the compiler at compile time(When the class
is not having a Constructor.
second one, we have to define that is called user defined Constructor.
Write a program to read values through the key board. Use Constructor.
#include<iostream>
using namespace std;
class num {
private:
int a,b,c;
public:
num(void); //declaration of constructor
void show() {
cout<<"\n"<<"a= "<<a<<" b= "<<b<<" c= "<<c;
}
};
Page 16
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
main() {
num x;
x.show();
return 0;
}
void show() {
cout<<"\n a= "<<a<<endl;
cout<<" b= "<<b<<endl;
}
};
main() {
test t;
t.show();
return 0;
}
Page 17
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
void show() {
cout<<"\n a= "<<a<<endl;
cout<<" b= "<<b<<endl;
cout<<"c= "<<c<<endl;
}
};
main() {
test t1(30,20,10);
t1.show();
return 0;
}
void show() {
cout<<" a= "<<a<<endl;
cout<<" b= "<<b<<endl;
cout<<"c= "<<c<<endl<<endl;
}
};
int main() { t1 t2
test t1(1,2,3); a=1
a=1
test t2(1,2);
test t3(1); b=2 b=2
test t4; c = 30
c=3
t1.show();
t2.show(); t3 t4
a=1 a=1
t3.show();
t4.show(); b = 20 b=2
return 0;
c = 30 c=3
}
Missing arguments are replaced with default values.
Page 18
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
3. Copy constructor:
The process of copying one object data in to another object is called as Copy Constructor.
A copy constructor is a constructor which is used to initialize the current values with another
object value.
Copy constructor is used to create another copy or xerox of one object.
Copy constructors are having reference type parameters.
Copy constructors are having class type parameters means object.
Copy constructors receives another object to initialize current object.
#include<iostream>
using namespace std;
class sample {
int a,b;
public:
sample(int x, int y) // parameterized constructor
{
a=x;
b=y;
}
void display( ) {
cout<<"a= "<<a<<endl;
cout<<"b= "<<b<<endl;
}
};
int main( ) {
sample s1(10,20);
sample s2(s1);
cout<<"Parameterized constructor"<<endl;
s1.display();
cout<<"copy constructor"<<endl;
s2.display();
return 0;
}
Page 19
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
Destructors :
When ever constructor is executed object is defined and memory is allocated.
Now to release (or) delete this memory we use destructor.
Destructor is also one special member function, which is used to delete the memory
created by the constructor.
Constuctor constructs the memory (or) Constructor constructs the object data.
Destructor is used to delete this memory created by constructor.
Using destructors is a good practice because it automatically release the memory
occupied by the constructor.
Rules:
1. Destructor name should be similar to class name and preceded by 'tilde' operator(~).
ex: class sample {
sample() //constructor
{
------
-----
}
~sample() //Destructor
{
------
------
}
};
2. Destructor should be declared in public section.
3. Destructor doesn't have any arguments, so overloading is not possible.
4. Destructor never returns a value, it makes a implicit call new and delete operator.
5. Destructor necer called with object followed by dot(.) operator.
6. Destructor never participate in inheritance.
Program to demonstrate destructor
#include<iostream>
using namespace std;
class sample {
int a,b;
public:
sample() { //constructor
a=10;
b=20;
}
~sample() { //destructor
cout<<"\n a= "<<a<<endl;
cout<<" b= "<<b<<endl;
}
};
Page 20
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-2
main() {
sample s;
return 0;
}
Note: Destructor is invoked when object is delete. Before going to delete data it prints the data.
Anonymous Objects:
Objects are created with names. It is possible to declare objects without name.
Such objects are called anonymous objects.
With out specifying object name we can initialize and destroy the members of the class.
We can also assume that the operations are carried out using an anonymous object , which
exists but is hidden.
write a program to create anonymous object initialize and display the contents of member
variables.
#include<iostream>
using namespace std;
class anonymous {
private:
int rollno;
float marks;
public:
anonymous() {
rollno=1201;
marks=76.8;
display();
}
~anonymous() {
cout<<" In destructor";
}
void display() {
cout<<"Roll no = "<<rollno<<endl;
cout<<"Marks = "<<marks<<endl;
}
};
int main() {
anonymous();
return 0;
}
Page 21
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
UNIT III
[Operator Overloading and Type Conversion & Inheritance]
The Keyword Operator, Overloading Unary Operator, Operator Return Type, Overloading
Assignment Operator (=), Rules for Overloading Operators, Inheritance, Reusability, Types of
Inheritance, Virtual Base Classes, Object as a Class Member, Abstract Classes, Advantages of
Inheritance-Disadvantages of Inheritance.
FRIEND FUNCTIONS: The private members cannot be accessed from outside the class. i.e., a
non member function cannot have an access to the private data of a class. In C++ a non
member function can access private members by making the function friendly to a class.
A friend function is not a member of any class, but it is able to access the private members of
those where it is introduced as a friend.
when a data is declared as private inside a class, then it is not accessible from outside the class.
A friend function is used for accessing the non-public members of a class. A class can allow
non-member functions and other classes to access its own private data, by making them
friends. Thus, a friend function is an ordinary function or a member of another class.
Definition:
A friend function is a function which is declared within a class and is defined outside the class.
It does not require any scope resolution operator for defining . It can access private members
of a class. It is declared by using keyword “friend”.
How to declare Friend Function in C++:
Friend function declaration should be inside the class using the Friend key word.
Syntax: friend ret_type func_name(arguments);
Definition of friend function is specified outside the class .
Function definition must not use keyword friend.
Friend function characterstics:
It is not in scope of class.
—It cannot be called using object of that class.
—It should use a dot operator for accessing members that is inside the friend function to access
friend int compute(sample s1); //Friend Function Declaration with keyword friend and with
the object of class sample to which it is friend passed to it
};
int compute(sample s1) { //Friend Function Definition which has access to private data
return int(s1.a+s1.b)-5;
}
int main() {
sample s ;
s.get();
cout<<"The result is:"<<compute(s)<<endl; //Calling of Friend Function with object as
argument.
return 0;
}
The output of the above program is
The result is:295
The function compute() is a non-member function of the class sample.
In order to make this function have access to the private data a and b of class sample, it is
created as a friend function for the class sample. As a first step, the function compute() is
declared as friend in the class sample as:
friend int compute (sample s1)
The keyword friend is placed before the function. The function definition is written as a normal
function and thus, the function has access to the private data a and b of the class sample. It is
declared as friend inside the class,
In function compute the private data values a and b are added, 5 is subtracted from the result,
giving 295 as the result. This is returned by the function and thus the output is displayed as
shown .
// Program to access private data using non-member function, by using Friend function.
#include<iostream>
using namespace std;
class account {
char name[20];
int acno;
float bal;
public :
void read() {
cout<<"\n Enter Name : ";
cin>>name;
cout<<"\n Enter Account No : ";
cin>>acno;
cout<<"\n Enter Balance : ";
cin>>bal;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
write a program to find max of two numbers using friend function for two different classes.
#include<iostream>
using namespace std;
class sample2;
class sample1 {
int x;
public:
void getx(){
cout<<"Enter X : ";
cin>>x;
}
friend void max(sample1 s1,sample2 s2); // max is a friend function with 2 class type objects.
};
class sample2 {
int y;
public:
void gety() {
cout<<"Enter Y : ";
cin>>y;
}
friend void max(sample1 s1,sample2 s2);
};
void max(sample1 s1,sample2 s2) {
if(s1.x>s2.y)
cout<<"Data member of class sample1 is larger"<<endl;
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
else if(s2.y>s1.x)
cout<<"Data member of class sample2 is larger"<<endl;
else cout<<"both are equal"<<endl;
}
int main() {
sample1 obj1;
sample2 obj2;
obj1.getx();
obj2.gety();
max(obj1,obj2);
return 0;
}
//program to declare friend function in two classes. Calculate the sum of integers of both the
classes using friend sum() function.
When a function is friend of more than one class then forward declaration of class is
needed so we are declaring class first;
#include<iostream>
using namespace std;
class first;
class second {
int s;
public:
void getvalue(){
cout<<"Enter S : ";
cin>>s;
}
friend void sum(second , first);
};
class first {
int f;
public:
void getvalue(){
cout<<"Enter F : ";
cin>>f;
}
friend void sum(second , first);
};
void sum(second d, first t) {
cout<<"Sum of two numbers : "<<t.f+d.s<<endl;
}
int main() {
first a;
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
second b;
a.getvalue();
etvalue();
sum(b,a);
return 0;
}
Explanation : In the above program, two classes first and second are declared with one
integer and one member function in each . The member function getvalue() of both classes
reads integers through keyboard. In both the classes the function sum() is declared as
friend. Hence this function has an access to the members of both the classes. Using sum()
function addition of two integers is calculated and displayed.
Friend Class
It is possible to declare one or more functions as friend functions or an entire class can
also be declared as friend class. A class can also be declared to be the friend of some other
class. When we create a friend class then all the member functions of the friend class also
become the friend of the other class. This requires the condition that the friend becoming
class must be first declared or defined (forward declaration).
// program to demonstrate friend classes.
//declare two friend classes and access the private data.
#include <iostream>
using namespace std;
class sample_1 {
int a,b;
public:
friend class sample_2; //declaring friend class
void getdata_1() {
cout<<"Enter A & B values in class sample_1: ";
cin>>a>>b;
}
void display_1() {
cout<<"A="<<a<<endl;
cout<<"B="<<b<<endl;
}
};
class sample_2 {
//public:
int c,d,sum;
sample_1 obj1;
public:
void getdata_2() {
obj1.getdata_1();
obj1.display_1();
cout<<"Enter C & D values in class sample_2 : ";
cin>>c>>d; }
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
void sum_2() {
sum=obj1.a+obj1.b+c+d;
}
void display_2() {
cout<<"A="<<obj1.a<<endl;
cout<<"B="<<obj1.b<<endl;
cout<<"C="<<c<<endl;
cout<<"D="<<d<<endl;
cout<<"SUM="<<sum<<endl;
}
};
int main() {
//sample_1 s1;
//s1.getdata_1();
//s1.display_1();
sample_2 s2;
s2.getdata_2();
s2.sum_2();
s2.display_2();
}
OPERATOR OVERLOADING
A symbol that is used to perform an operation is called an operator. It is used to perform an
operation with constants and variables. A programmer cannot build an expression without
an operator. The compiler knows how to perform various operations using operators for the
built-in types, however, for the objects those are instance of the class, the operation routine
must be defined by the programmer.
Keyword operator
The keyword operator defines a new operation (or) action to the operator.
In C++, we can change the way operators work for user-defined types like objects and structures.
This is known as operator overloading.
syntax:
return-type operator operatorsymbol(parameter list)
{
statement 1;
statement 2;
.
.
statement n;
}
Here,
returnType is the return type of the function.
operator is a keyword.
operatorsymbol is the operator we want to overload. Like: +, <, -, ++, etc.
parameters is the arguments passed to the function.
The keyword "operator", followed by a symbol, defines a new (overloaded) action of the given
operator.
Note: We cannot use operator overloading for fundamental data types like int, float, char and
so on.
Example :
void operator ++();
void operator --();
void operator +();
void operator -();
void operator ++(num);
void operator -(num,num);
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
The keyword operator followed by an operator symbol defines a new action of the given
operator.
Operator function should be either member function or friend function.
A friend function requires one parameter for unary operation and two parameters for
binary operation.
The member function requires no parameter for unary operation and one parameter
for binary operation.
When a member function is called the calling object is passed implicitly to that function and it
is available for that member function.
//Write a program to perform addition of two objects by using key word operator.
#include<iostream>
using namespace std;
class number {
public:
int x,y;
number() //zero argument constructor
{
}
number(int j, int k) //two argument constructor
{
x=j;
y=k;
}
number operator +(number D) {
number T;
T.x=x+D.x;
T.y=y+D.y;
return T;
}
void show() {
cout<<"\n X= "<<x<<" Y= "<<y;}
};
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
int main() {
number A(2,3),B(4,5), C;
A. show();
B. show();
C=A+B;
C. show();
}
Explanation :
In the above program, A,B,C are objects of class number. Using constructor, objects are
initialized.
here, we performed addition using stmt C=A+B.
Whenever the stmt C=A+B is executed, the compiler searches for definition of
operator +() function. The object A invokes the operator function and object B is passed
as argument. The copy of object B is stored in the formal argument D. The member
variables of A are directly available in operator function as the function is invoked by the
same object. The addition of individual members are carried out and stored in member
variable of object T. The return type of operator function is same as that of its class. The
function returns object T and it is assigned to variable C.
int main() {
number A(2,3),B(4,5), C;
A. show();
B. show();
C=A-B;
C. show();
}
Example 1:-
void operator++()
{
counter++;
}
Example 2:-
void complex::operator-()
{
real=-real;
img=-img;
}
The unary ++ when applied to an object should increment each of its data items.
public:
number(int j, int k, int m, int l) {
a=j;
b=k;
c=m;
d=l;
}
void show(void);
void operator ++();
};
void number::operator ++() {
++a; ++b;++c;++d;
}
void number::show() {
cout<<"\n A= "<<a<<" B= "<<b<<" C= "<<c<<" D= "<<d<<endl;
}
int main() {
number X(3,2,5,7);
cout<<"\n Before Increment of X : ";
X.show();
++X;
cout<<"\n After Increment of X : ";
X.show();
return 0;
}
Explanation : In the above prog the class num contains four integer variables a,b,c, and d.
The class also has two member functions show() and operator++() and one parameterized
constructor. The constructor is used to initialize object. The show() displays the contents of
the member variables. The operator ++() overloads the unary operator ++. when this
operator is used with integer or float variables, its value is increased by one. In this function,
++ operator precedes each member variable of class. This operation increments the value of
each variable by one.
In function main() ,the stmt ++X calls the function operator ++(), where X is an object of the class
num. The function can also be called using stmt X. operator ++().
In the output, values of member variables before and after increment operations are displayed.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
int main() {
plusplus p1,p2;
cout<<"\n p1 = "<<p1.getnum();
cout<<"\n p2 = "<<p2.getnum();
p1=p2++;
cout<<"\n p1 = "<<p1.getnum();
cout<<"\n p2 = "<<p2.getnum();
p1++;
cout<<endl<<" p1 = "<<p1.getnum();
cout<<endl<<" p2 = "<<p2.getnum();
return 0;
}
Explanation: In this program class plusplus is declared with one private integer num. The
class constructor initializes the object with zero. The member function getnum() returns
current increment of the objects. p1 and p2 are objects of the class plusplus.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
#include<iostream>
using namespace std;
class number {
int a,b,c,d;
public:
number(){a=b=c=d=0;}
number(int j, int k, int m, int l) {
a=j;
b=k;
c=m;
d=l;
}
void show(void);
friend number operator ++(number);
};
number operator ++(number n) {
n.a=++n.a;
n.b=++n.b;
n.c=++n.c;
n.d=++n.d;
return n;
}
void number::show() {
cout<<"\n A= "<<a<<" B= "<<b<<" C= "<<c<<" D= "<<d<<endl;
}
int main() {
number X(3,-2,5,-7),N;
cout<<"\n Before Increment of X : ";
X.show();
N=++X;
//X.operator++();
cout<<"\n After Increment of X : ";
N.show();
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
// Write a C++ program to overload unary operator in complex numbers by using friend
function
#include<iostream>
using namespace std;
class complex {
float real,imag;
public:
complex(){
real=imag=0;
}
complex(float r, float i) //two argument constructor
{
real=r;
imag=i;
}
void show(void){
cout<<"\n Real= "<<real;
cout<<"\n Imag= "<<imag<<"i";
}
friend complex operator -(complex);
};
complex operator -(complex c) {
c.real=-c.real;
c.imag=-c.imag;
return c;
}
//void number::show() { }
int main()
{
complex c1(3.2 , 5.7) , c2;
cout<<"\n Before Negation : ";
c1.show();
c2=-c1;
cout<<"\n After Negation of X : ";
c2.show();
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
int main() {
Complex c1,c2, sum; //Created Object of Class Complex i.e c1 and c2
c1.input(); //reading the values
c2.input();
sum = c1+c2; //Addition of object
cout<<"\n Entered Values : \n";
cout<<"\t";
c1.display(); //Displaying user input values
cout<<"\t";
c2.display();
cout<<"\n Addition of Real and Imaginary Numbers : \n";
cout<<"\t";
sum.display(); //Displaying the addition of real and imaginary numbers
return 0;
}
Explanation :
In the above program the class name is Complex it has two private data members num1 ,num2 and
three member functions , the input() member function reads the values and assign it to num1 and
num2. display() member function is used to display the user input values. here we are over loading
binary + operator and inside the operator +() function
the stmt sum = c1+c2 invokes the operator function , in this stmt object c2 is assigned to formal
parameter c2 of operator function and member variables of c1 are accessed directly.
The object c is used for holding the result of addition, and it is returned to object sum. and the
function display() displays the values of c1,c2 and sum.
While overloading a binary operator using friend function, argument list must take 2
arguments.
#include<iostream>
using namespace std;
class Complex {
int num1, num2;
public:
void input() {
cout<<"\n Enter Two Complex Numbers : ";
cin>>num1>>num2;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
Explanation :
In the above program the class name is Complex it has two private data members
num1 ,num2 and three member functions , the input() member function reads the
values and assign it to num1 and num2. display() member function is used to display
the user input values. here we are over loading binary + operator using friend function
so in side the class complex the operator +() function is declared as friend While
overloading a binary operator using friend function, argument list must take 2
arguments , friend function definition must be outside the class.
inside the operator +() function , addition of member variables of two objects is
performed and results are assigned to member variables of third object. In this
program c1,c2,sum are objects of class complex.
the stmt sum = c1+c2 invokes the operator function , in this stmt object c1 is assigned to
formal parameter c1 ,object c2 is assigned to formal parameter c2 of operator function to
access the member variables of class.
The object c is used for holding the result of addition, and it is returned to object sum. and the
function display() displys the values of c1,c2 and sum.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
int main() {
num a1(2) , a2(8);
cout<<"\n Before overloading assignment operator:";
cout<<"\n A = ";
a1.show();
cout<<"\n B = ";
a2.show();
a2=a1;
cout<<"\n After overloading assignment operator implicitly(b=a):";
cout<<"\n A = ";
a1.show();
cout<<"\n B = ";
a2.show();
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
INHERITANCE
Inheritance is one of the most important and useful characteristics of OOP. Literally
inheritance means adopting features by newly created thing from the existing one.
The process of obtaining data members and methods from one class to another class i.e., one
class to acquire properties and characteristics from another class is known as inheritance.
In OOP inheritance can be defined as the as the process of creating a new class from one or
more existing classes. The existing class is known as base class or parent class or super class
where as newly created class is known as derived class or child class or sub class. Inheritance
provides a significant advantage in terms of code reusability. Consider the diagram shown
below
Base class
derived class
In the above ,a new class B is derived from an existing class A using the feature inheritance.
Due to this the derived class B inherits the features of base class A. The derived classes has all
the features of the base class and the programmer can choose to add new features specific to
the newly created derived class.
However, the derived class can also have its own features.
Inheritance makes the code reusable. Now the term reusability means, When we inherit an
existing class, all its methods and fields become available in the new class, hence code is
reused. that is the derived class object can access the base class members also. However, the
reverse of this is not true I,e the base class object can not access the derived class members as
the base class is not aware of derivation of derived class.
(All the members of base class are inherited except the private members.)
Base class and Derived class
The existing class from which the derived class gets inherited is known as the base class. It acts
as a parent for its child class and all its properties I,e public and protected members get
inherited to its derived class.
A derived class can be defined by specifying its relationship with the base class in addition to
its own details i.e., members
The general form of defining a derived class is
class derived-class-name: access-specifier base-class-name
{
//members of the derived class
};
The access specifier determines how elements of the base class are inherited by the derived
class. (or)access specifier define how can the derived class access the Base class members .
Here access is one of the three keywords: public, private and protected.
Base class accesibility is dependent on the visibility mode of derived class.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
Modes of inheritance :
1. Public Mode: If we derive a sub class in public mode. Then the public member of the base
class will become public in the derived class and the protected members of the base class
will become protected in derived class.
2. Protected Mode: If we derive a sub class in protected mode. Then both public member and
protected members of the base class will become protected in derived class.
3. Private Mode: If We derive a sub class in private mode. Then both public member and
protected mem bers of the base class will become private in derived class
In all cases, private members of a base class remain private to that base class.
It is important to understand that if the access specifier is private, public members of the base
become private members of the derived class. If access specifier is not present, it is private by
default.
Protected:
This access modifier plays a key role in inheritance.
Protected members of the class can be accessed within the class and from derived class
Types of Inheritance:
Single Inheritance If a class is derived from a single class then it is called single
inheritance.
Class B is derived from class A
A
B
derived from class A, so it is called multilevel inheritance.
C
Multiple Inheritance If a class is derived from more than one class then it is
called multiple inheritance.
Here, class C is derived from two classes, class A and
A B class B.
Hierarchical Inheritance If one or more classes are derived from one class then it
is called hierarchical inheritance.
Here, class B, class C and class D are derived from class A.
A
B C D
Single inheritance: One derived class inherits from only one base class. The process in which a
derived class inherits traits from only one base class, is called single inheritance. In single
inheritance, there is only one base class and one derived class. The derived class inherits the
behavior and attributes of the base class. The derived class can add its own properties, ie data
members(variables) and functions. It can extend or use properties of the base class with out
any modification to the base class.
Syntax:
class base_class
{
};
class derived_class:visibility-mode base_class
{
};
int main() {
physique p;
p.getdata();
p.show();
return 0; }
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
Multilevel inheritance
In this type of inheritance a single derived class may inherit from two or more than two base
classes. The process in which a derived class inherits traits from another derived class, is called
multilevel inheritance.
syntax: base class
class A
{
……
}; intermedite class
class B:public A
{
……….
derived class
};
class C:public B
{
…….
};
Here, class B is derived from class A. Due to this inheritance, class B adopts the features of base
class A. Additionally, class B also contains its own features, Further, a new class, class c is
derived from class B, Due to this ,class c adopts the features of class B, as well as features of
class A.
Multiple inheritance
The process in which derived class inherits traits from several base classes, is called multiple
inheritance. In multiple inheritance, there is only one derived class and several base classes.
we declare the base classes and derived class as given.
Syntax:
class base_class1{
};
class base_class2{
};
class derived_class: visibility-mode base_class1,visibility-mode base-class2 {
};
Program to illustrate the concept of multiple inheritance
#include<iostream>
using namespace std;
class student {
int id;
char name[20];
public:
void getstudent() {
cout<<"Enter Student id and name : ";
cin>>id>>name;
}
void putstudent() {
cout<<"ID = "<<id<<endl;
cout<<"NAME = "<<name<<endl;
}
};
class marks {
protected:
int m1,m2,m3;
public:
void getmarks(){
cout<<"Enter marks of 3 subjects";
cin>>m1>>m2>>m3;
}
void putmarks() {
cout<<"M1= "<<m1<<endl;
cout<<"M2= "<<m2<<endl; int main() {
cout<<"M3= "<<m3<<endl; result r;
}
r.getstudent();
};
r.getmarks();
class result:public student,public marks { r.putstudent();
int total;
r.putmarks();
float avg; r.show();
public: return 0;
void show() { }
total=m1+m2+m3;
avg=float(total)/3;
cout<<"TOTAL= "<<total<<endl;
cout<<"AVERAGE= "<<avg<<endl; } };
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
Hierarchical Inheritance
In this type of inheritance,more than one sub class is inherited from a single base class.i,e more
than one derived class is created from a single base class.
syntax:
class base-class-name {
data members;
member functions;
};
class derived-class-name1:visibility mode base-class-name
{
data members;
member functions;
};
class derived-class-name2:visibility mode base-class-name
{
data members;
member functions;
}
Note: visibility mode can be either private,public or protected
Hybrid inheritance: The combination of one or more type of inheritance happening together is
known as hybrid inheritance.
The following diagram explains the concept in better way.
In the diagram, the derivation of class B from
class A is single inheritance.
The derivation of class C from class B , class D
is multiple inheritance.
int main() {
B two;
two.show();
return 0;
}
Explanation: In the above program, the class B contains integer y and object one of class A.
in function main(), object two is an object of class B. The constructor of class A is executed
first, because when the compiler reaches the class B, it finds an object of class A. We know that
the object declaration always executes the constructor of that class. Thus, the object of class A
is declared, and the constructor of class A is executed. The constructor of class B is executed,
and the variables of class B is initialized. The member function show() displays the contents
of x and y. the content of class A member is obtained from object one.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
ABSTRACT CLASS
When a class is not using for creating an object such class is known as abstract class.
The abstract class can act as a base class only.
An abstract class gives a skeleton or a structure, using this other classes are shaped.
A class which contains pure virtual function is called abstract base class.
// Abstract class
#include<iostream>
using namespace std;
class base {
public:
virtual void display()=0;
int x;
};
class derived : public base {
public:
void display()
{
cout<<"\n In derived class ";
}
};
int main() {
base *b;
derived d;
b = &d;
b->display();
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
ADVANTAGES OF INHERITANCE
When a class inherits from another class, there are three benefits:
1. You can reuse the methods and data of the existing class .
The most frequent use of inheritance is for deriving classes using existing classes, which
provides reusability. The existing classes remain unchanged. By reusability, the
development time of software is reduced.
The same base classes can be used by a number of derived classes in class hierarchy.
2. You can extend the existing class by adding new data and new methods.
The derived classes extend the properties of base classes to generate more dominant
objects.
When a class is derived from more than one class, all the derived classes have similar
properties to those of base classes.
3. You can modify the existing class by overloading its methods with your own
implementations
DISADVANTAGES OF INHERITANCE
1. Though object -oriented programming is frequently propagandized as an answer for
complicated projects, inappropriate use of inheritance makes programs more complicated.
2. Invoking member functions using objects creates more compiler overheads.
3. In class hierarchy, various data elements remain unused, and the memory allocated to them
is not utilized.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
TYPE CONVERSION
Converting data from one type into another type is called type conversion.
Example: - int m;
float x=3.141;
m = x ; // conversion of float type data into integer.
here m is integer x is float and the stmt m = x , here we want to store float value in to an
integer data type, compiler will automatically convert float value in to integer after that it will
store in to integer value m. This is done by compiler there fore it is called implicit type
conversion or automatic type conversion.
Different types of Type conversion:
There are four types of type conversion:
1. Conversion from basic type to basic type.
2. Conversion from basic type to class type.
3. Conversion from class type to basic type.
4. Conversion from class type to class type.
1. Conversion from basic type to basic type:
This type of conversion can be done in two ways :
Implicit (Automatic )
Explicit( by Programmer)
Automatic(implicit) Type conversion : This is done by the compiler from the type that doesn't
fit, to the type it wants.
Example : - int i;
float f=3.141;
i = f ; // implicit type conversion of float type data into integer.
Explicit Type Conversion :
Explicit type conversion done by the programmer from the type that doesn't fit, to the type it
wants.
Example : - int i=3;
float f;
f = float(i)/2; //Explicit type conversion of integer to float.
2. Conversion from Basic to class type :
In c++ conversion of basic type to class type can be done using constructor. By creating a
constructor the basic data type integer, float can be converted in to an object. conversion is
automatically done by the compiler, by applying type casting.
In this , the left-hand operand of = sign is always class type and the right - hand operand is
always basic type.
#include<iostream>
using namespace std;
class hours {
int hrs;
float f;
public:
hours(int t) {
hrs=t/60;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
void show() {
cout<<hrs<<" hours "<<endl;
}
};
int main() {
hours t1 = 125;
t1.show();
return 0;
}
Explanation: The class name is hours . inside class we have declared a private variable hrs. we
have declared a parameterized constructor by passing an integer value and this value is
assigned to data member hrs. here actually we are converting a basic data type to object . The
stmt hours t1 = 125, here t1 is object, 125 is an integer value, this integer value is going to be
stored in to object. and this done by calling a parameterized constructor , so when the stmt
hour t1 = 125 is executed the type casting is performed. i.e, a type conversion is performed
with the help of constructor. at this step constructor is called 125 is passed as argument to
constructor and inside the constructor hrs = t/60; hrs have integer value and using the object
t1 we are printing the result. so here stmt hours t1 = 125 is representing the basic type to class
type conversion . t1.show() will display o/p.
int main() {
float f;
hours t1 = 185; //integer 185 is converted into object of class hrs
t1.show();
f=t1; // type conversion from class object "t1" to float "f"
cout<<"time = "<<f<<endl;
return 0;
}
Explanation : The class name is hours . inside class we have declared a private variable hrs. we
have declared a parameterized constructor by passing an integer value and this value is
assigned to data member hrs. here we have written a casting operator function , you can see
there is no return type , and no parameters passed to it. in side the body of this casting function
we are returning a float value so, our object will be converted to float value. so we can say our
class type can be converted to basic data type. i.e, hours object is converted in to a float variable.
In main() function the stmt hrs t1 = 185; is basic to class type conversion
the stmt f=t1; here you can see class type to basic type , t1 is object of class and f is a float
variable.
when the stmt f=t1 is executed the casting operator is called. in side this casting operator
function the value of hrs/2 is converted to float and it is returned, the float value is returned by
object t1 and it is stored in float variable f.
this is how a class type is converted to basic type with the help of casting operator function.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
Example : Program to convert class type to class type using conversion operator function in
source class. (Using constructor)
#include<iostream>
using namespace std;
class minutes //source class
{
int m;
public:
minutes(int ms) {
m=ms;
}
void show() {
cout<<"Minutes= "<<m<<endl;
}
int getdata() {
return m;
}
};
class hours { //destination class
int h;
public:
hours() {
h=0;
}
void show() {
cout<<"Hours=
"<<h<<endl;
}
hours(minutes mm) {
h=mm.getdata()/60;
}
};
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-3
int main() {
minutes min(70);
hours hr;
hr=min; // class minutes to class hours
min.show();
hr.show();
return 0;
}
UNIT IV
[Pointers & Binding Polymorphisms and Virtual Functions]
Pointer, Features of Pointers, Pointer Declaration, Pointer to Class, Pointer Object, The this
Pointer, Pointer to Derived Classes and Base Class, Binding Polymorphisms and Virtual
Functions, Binding in C++, Virtual Functions, Rules for Virtual Function, Virtual Destructor.
FEATURES OF POINTER :
pointers save memory space.
Execution time with pointers is faster, because data are manipulated with the address,
that is direct access to memory.
Memory is accessed efficiently with the pointers.
The pointer assigns as well as releases the memory space.
Memory is dynamically allocated.
Pointer are used with data structures.
They are useful for representing two-dimensional and multi - dimensional array.
In c++ a pointer declared to a base class could access the object of a derived class,
how ever , a pointer to a derived class cannot access the object of base class.
POINTER DECLARATION
Pointer variables can be declared as follows:
Example:
int *x;
float *f;
char *y;
in the first statement 'x' is an integer pointer, and it informs the compiler that it holds the
address of any integer variable. In the same way 'f' is a float pointer that stores the address of
any float variable, in the same way character pointer which stores the address of any
character variable.
Normal variables provide direct access to their own values, where as a pointer indirectly
accesses the value of a variable to which it points.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
// Write a program to display the value and address of the variable using pointer.
#include<iostream>
using namespace std;
int main() {
int *p;
int x=10;
p=&x;
cout<<"\n x= "<<x<<" &x= "<< &x;
cout<<"\n *p= "<<*p<< "\t &p= "<<p<<"\t(Contents of pointer)"<<endl;
return 0;
}
POINTER TO CLASS
Pointer is a variable it holds address of another variable and it may be of any data type i.e.,
int , float , double ....
Similarly we can also define a pointer to a class.
Example:- class student {
int id;
int age;
};
class student *ptr;
In the above example ptr is a pointer to class student.
The syntax for using pointer with member is given below
ptr -> id
ptr -> age
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
Write a program to declare a class and declare pointer to class and display the contents of class
members.
//Pointer to class
#i nclude<iostream>
using namespace std;
class student{
public:
char name[20];
int id;
int age;
};
int main() {
class student s1={"Ravi",1210,21};
student *ptr;
ptr=&s1;
cout<<"\n Student Name= "<<ptr->name<<endl;
cout<<" Student id= "<<ptr->id<<endl;
cout<<" Student Age= "<<ptr->age<<endl;
return 0;
}
POINTER OBJECT
Similar to variables, objects also have an address.
A pointer can point to a specified object.
When accessing members of a class given a pointer to an object, use the arrow(->) operator
instead of the dot operator.
Write a program to declare an object and pointer to the class. Invoke the member function
using pointer.
#include<iostream>
using namespace std;
class student {
char name[20];
int id;
int age;
public:
void getstudent() {
cout<<"Enter Student Name: ";
cin>>name;
cout<<"Enter Student ID: ";
cin>>id;
cout<<"Enter Student Age: ";
cin>>age;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
void putstudent() {
cout<<"\n Student Name= "<<name<<endl;
cout<<" Student id= "<<id<<endl;
cout<<" Student Age= "<<age<<endl;
}
};
int main() {
class student s1;
student *ptr;
ptr=&s1;
ptr->getstudent();
ptr->putstudent();
return 0;
}
cout<<"Obj addr = "<<this<<endl;//this will display the current obj addr in hexa decimal
cout<<"a= "<<this->a<<endl;
cout<<"b= "<<this->b<<endl;;
}
};
int main() {
sample s;
s.show();
return 0;
}
output:
obj addr = 0x28ff08
a=10
b=20
Example 2:
//this pointer
#include<iostream>
using namespace std;
class sample {
int a,b;
public:
get(int a, int b) {
this->a=a;
this->b=b;
}
void display() {
cout<<"A= "<<a<<endl;
cout<<"B= "<<b<<endl;
}
};
int main() {
sample s;
s.get(10,20);
ispl
ay()
;
retu
rn
0;
}
out put:
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
A=10
B=20
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
Example 3:
//this pointer
#include<iostream>
using namespace std;
class sample {
int a;
public: sample() {
a=10;
}
void disp(int a) {
cout<<"The value of argument a="<<a;
cout<<"\nThe value of data member a="<<this->a;
}
};
int main() {
sample S;
S.disp(20);
return 0;
}
out put:
The value of argument a= 20
The value of data member a= 10
// Write a program to declare a pointer to the base class and access the member variable of
base and derived class.
//pointer TO BASE CLASS
#include<iostream>
using namespace std;
class base {
public: int b;
void show() {
cout<<"\nThe value of b : "<<b;
} };
class derived:public base {
public: int d;
void show() {
cout<<"\nThe value of b="<<b
<<"\nThe value of d="<<d;
} };
int main() {
base B;
base *bptr;
bptr=&B;
cout<<"\nBase class pointer assign address of base class object";
bptr->b=100;
//bptr->d=200;
bptr->show();
derived D;
bptr=&D;
cout<<"\nBase class pointer assign address of derived class object";
bptr->b=200;
//bptr->d=300;
bptr->show();
return 0;
}
output :
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
int main() {
derived D;
derived *dptr;
dptr=&D;
dptr->b=200;
dptr->d=300;
cout<<"\nDerived class pointer assign address of derived class object";
dptr->show();
return 0;
}
out put:
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
// Write a program to declare a pointer to the derived class and access the member variable of
base and derived class.
#include<iostream>
using namespace std;
class base {
public: int b;
void show() {
cout<<"\nThe value of b : "<<b;
}
};
class derived: public base {
public: int d;
void show() {
cout<<"\nThe value of b="<<b
cout<<"\nThe value of d="<<d;
}
};
int main() {
base B, *bptr;
derived D;
bptr=&B;
cout<<"\nBase class pointer assign address of base class object";
bptr->b=100;
bptr->show(); bptr=&D;
bptr->b=200;
cout<<"\nBase class pointer assign address of derived class object";
bptr->show();
derived *dptr;
dptr=&D;
cout<<"\nDerived class pointer assign address of derived class object";
dptr->d=300;
dptr->show();
return 0;
}
out put:
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
What is Binding?
For every function call, compiler binds or links the call to one function definition. This
linking can happen at 2 different time
At the time of compiling program, or
At Runtime
Deciding a function call at compile time is called as compile time (or) static (or) early
binding. Deciding a function call at run time is called as run time (or) dynamic (or) late
binding.
FUNCTION OVERLOADING:
• Function overloading is declaring the same function with different signatures.
that is defining several functions with same name, by changing no.of arguments, type
of arguments(data types) and order of arguments,
• The same function name will be used with different number of parameters and
parameters of different type.
• Overloading of functions with different return type is not allowed.
OPERATOR OVERLOADING:
• Operator overloading is the ability to tell the compiler how to perform a certain
operation based on its corresponding operator's data type.
• Like + performs addition of two integer numbers, concatenation of two string
variables and works totally different when used with objects of type class.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
It would be nice if the appropriate member function could be selected while the
program is running. This is known as runtime polymorphism. C++ supports a
mechanism known as virtual function to achieve run time polymorphism.
At the runtime, when it is known what class objects are under consideration, the
appropriate version of the function is invoked. Since the function is linked with a
particular class much later after the compilation, this process is termed as late
binding. It is also known as dynamic binding because the selection of the
appropriate function is done dynamically at run time.
In late binding, call to a function is resolved at Runtime, the compiler determines
the type of object at execution time and then binds the function call to a function
definition.
It means that the code associated with a given procedure call is not known until
the time of thecall.
At run-time, the code matching the object under current reference will be called.
Late binding is also called as Dynamic Binding or Runtime Binding.
Virtual Functions are example of Late Binding in C++
Runtime polymorphism is achieved using pointers.
VIRTUAL FUNCTIONS
Polymorphism refers to the property by which objects belonging to different classes are
able to respond to the same message, but different forms. An essential requirement of
polymorphism is therefore the ability to refer to objects without any regard to their classes.
When we use the same function name in both the base and derived classes, the function
in the base class is declared as virtual using the keyword virtual preceding its normal
declaration.
When a function is made virtual, C++ determines which function to use at runtime based on
the type of object pointed to by the base pointer, rather than the type of the pointer. Thus, by
making the base pointer to point to different objects, we can execute different versions of the
virtual function.
#include<iostream>
using namespace std;
class Base {
public:
void display() {
cout<<"Display Base"<<endl;
}
virtual void show() {
cout<<"Show Base"<<endl;;
}
};
class Derived : public Base {
public:
void display() {
cout<<"Display Derived"<<endl;;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
void show() {
cout<<"show derived"<<endl;
}
};
int main() {
Base b;
Derived d;
Base *ptr;
cout<<"ptr points to Base"<<endl;
ptr=&b;
ptr->display(); //calls Base
ptr->show(); //calls Base
cout<<"ptr points to derived"<<endl;
ptr=&d;
ptr->display(); //calls Base
ptr->show(); //class Derived
return 0;
}
Output:
When ptr is made to point to the object d, the statement ptr->display(); calls only
the function associated with the Base i.e.. Base::display()
#include<iostream>
using namespace std;
class circle
{
protected:
float radius;
public:
circle(float r)
{
radius=r;
}
virtual float area() {
float a;
a=3.14*radius*radius;
return a;
}
};
class cylinder : public circle
{
private:
float height;
public:
cylinder(float r, float h): circle(r)
{
height =h;
}
float area() {
float a;
a=(2*3.14*radius*radius)+(2*3.14*radius*height);
return a;
}
};
int main() {
circle *ptr;
circle ciobj(8);
cylinder cyobj(8,4);
ptr=&ciobj;
cout<<"Area of circle : "<<ptr->area()<<endl;
ptr=&cyobj;
cout<<"Area of cylinder : "<<ptr->area();
return 0;
}
out put:
Area of circle : 200.96
Area of cylinder :602.88
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
Definition Methods having same name but Sub class have method with same name and
each must have different number of exactly the same number and type of
parameters or parameters having parameters and same return type as super
different types & order. class method.
Meaning More than one method shares the Method of base class is re-defined in the
same name in the class but having derived class having same signature.
different signature.
Behaviour To Add/Extend more to To Change existing behaviour
method’s behaviour. of method.
Polymorphism Compile Time Run Time
No of Classes Does not require more than one Requires at least 2 classes
class for overloading. for overriding.
Example
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-4
#include <iostream>
using namespace std;
class employee {
int code;
char name [20];
public:
virtual void getdata ( )=0;
virtual void display ( )=0;
};
Example: A derived class object is constructed using a new operator. The base class pointer
object holds the address of the derived object. when the base class pointer is destructed using
the delete operator, the destructor of the base and derived class is executed.
The following program illustrates this
#include<iostream>
using namespace std;
class Base {
public:
Base() {
cout<<"Base class constructor"<<endl;
}
virtual ~Base () {
cout<<"Base class destructor"<<endl;
}
};
UNIT V
[Generic Programming with Templates]
Need for Templates, Definition of class Templates, Normal Function Templates, Overloading of
Template Function, Bubble Sort Using Function Templates, Difference Between Templates and
Macros, Linked Lists with Templates, Exception Handling, Principles of Exception Handling,
The Keywords try throw and catch, Multiple Catch Statements – Specifying Exceptions.
TEMPLATES in C++(GENERICS):
The template is one of the most useful characteristics of the C++.
The template provides generic programming by defining generic classes.
In templates, generic data types are used as arguments, and they can handle a variety of data
types.
A function that works for all C++ data types is called a generic function.
FUNCTION TEMPLATES
The templates declared for functions are called as function templates.
A function template defines how an individual function can be constructed.
Templates in array:
program to find the sum of integer array, float array.
#include<iostream>
using namespace std;
template<class T>
T sum(T a[], int size)
{
T s=0;
for(int i=0;i<size;i++)
{
s=s+a[i];
}
return s;
}
int main()
{
int x[5]={10,20,30,40,50};
float y[3]={1.1,2.2,3.3};
cout<<"Sum of Integer array = "<<sum(x,5)<<endl;
cout<<"Sum of Float array = "<<sum(y,3)<<endl;
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-5
CLASS TEMPLATES
The templates declared for classes are called class templates. A class template specifies how
individual classes can be constructed similar to the normal class specification. These
classes model a generic class which support similar operations for different data types.
General Form of a Class Template
template <class T>
class class-name
{
…….
…….
};
A class created from a class template is called a template class.
The syntax for defining an object of a template class is:
classname<type> objectname(arglist);
The statement template<class T> tells the compiler that the following class declaration can use
the template data type. The T is a variable of template type.
Templates cannot be declared inside the classes or functions. They should be global and should
not be local.
Write a program to show values of different data types using overloaded constructor.
#include<iostream>
using namespace std;
class data {
public :
data(char c)
{
cout<<"\n C= "<<c<<" Size in bytes: "<<sizeof(c);
}
data(int c)
{
cout<<"\n C= "<<c<<" Size in bytes: "<<sizeof(c);
}
data(double c)
{
cout<<"\n C= "<<c<<" Size in bytes: "<<sizeof(c);
}
};
int main() {
data h('A'); //passes character type data
data i(100); //passes integer type data
data j(68.2); //passes double type data
return 0;
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-5
Write a program to show values of different data types using constructor and template
#include<iostream>
using namespace std;
template<class T>
class data {
public :
data(T c)
{
cout<<"\n C= "<<c<<" Size in bytes: "<<sizeof(c);
}
};
int main() {
data <char> h('A');
data <int> i(100);
data <float> j(68.2);
return 0;
}
Note: When template class member function definition is outside it should once again
start with
template <class T>
return type class name<T> :: functionname
Example
Consider an array A of 5 element
A[0] 45
A[1] 34
A[2] 56
A[3] 23
A[4] 12
45 34 34 34 34
34 45 45 45 45
56 56 56 23 23
23 23 23 56 12
12 12 12 12 56 Largest element
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-5
45 45 23 23
23 23 45 12
23 34 12
56 56 56
23 12
12 23
34 34 Sorted Array
45 45
56 56
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-5
Write a program to sort the given elements by using bubble sort using template function
#include<iostream>
using namespace std;
//Declaration of template class
template<class B>
B bsort(B a[], int n) {
int i, j;
//bubble sort algorithm inside template
for(i=0;i<n-1;i++)
{
for(j=0;j<(n-i-1);j++)
{
if(a[j]>a[j+1])
{
B b;
b=a[j];
a[j]=a[j+1];
a[j+1]=b;
}
}
}
}
int main() {
int arr[20],m,k,i;
char ch[20];
cout<<"Enter what type of elements you want to sort :\n1. int\n2. char\n";
cin>>m;
if(m==1) {
cout<<"\nEnter the number of elements you want to enter:";
cin>>k;
cout<<"\nEnter Integer elements:";
for(i=0;i<k;i++)
cin>>arr[i];
bsort(arr,k); //call to bubble for integer sorting
cout<<"\nSorted Order Integers: ";
for(i=0;i<k;i++)
cout<<arr[i]<<"\t";
}
else {
cout<<"\nEnter the number of characters you want to enter:";
cin>>k;
cout<<"\nEnter elements:";
for(i=0;i<k;i++)
cin>>ch[i];
bsort(ch,k); //call to bubble for character sorting
cout<<"\nSorted Order Characters: ";
for(i=0;i<k;i++)
cout<<ch[i]<<"\t";
}
return 0; }
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-5
Exception Handling:
In programming two most common types of errors are
1. Compile time errors (or) syntax errors.
2. Run time error (or) logical error
The syntax error is detected during compilation of program, but the logical error will
detect during execution of program. So, it is very difficult to handle logical error.
These logical errors are also known as exceptions.
Exceptions were considered to be dangerous because when ever they occur the
program terminates abnormally on the line where the exception occur, with out
executing the next lines of code.
Exception Handling Mechanism:
It is an approach which stops the abnormal termination of a program when ever an
exception raises and executes the code which was not related with the exception.
The Keywords try throw and catch:
The exception-handling technique passes the control of a program from a location of
exception in a program to an exception-handler routine linked with try block.
An-exception-handler routine can only be called by the throw statement.
(a) try : The try keyword is followed by a series of statements enclosed in curly
braces.
Syntax of try statement:
try
{
statement 1;
statement 2;
}
(b) throw: The function of the throw statement is to send the exception found. The
declaration of the throw statement is as follows :
Syntax of throw statement :
throw (excep);
throw excep;
throw // re-throwing of an exception
The argument excep is allowed to be of any type, and it may be a constant. The
catch block associated with the try block catches the exception thrown. The throw
statement can be placed in a function or in a nested loop, but it should be in the try
block. After throwing the exception , control passes to the catch statement.
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-5
(c) catch: Similar to the try block, the catch block also contains a series of statements
enclosed in curly braces. It also contains an argument of an exception type in
parantheses.
Syntax of catch statement:
try
{
statement 1;
statement 2;
}
catch (argument)
{
statement 3; //Action to be taken
}
When an exception is found, the catch block is executed. The catch statement
contains an argument of exception type, and it is optional. When an argument is
declared, the argument can be used in the catch block. After the execution of the
catch block, the statements inside the blocks are executed. In case no exception is
caught, the catch block is ignored, and if a mismatch is found, the program is
terminated.
Exception handling mechanism is built upon three keyword: try, throw and catch.
try is used to preface a block of statement which may generate exceptions.
When an exception is detected, it is thrown using a throw statement.
A catch block is used to catch the exceptions thrown by throw statement and take
appropriate action. The relationship between try, throw and catch block is as shown
in below figure.
try block
Detects and
throws an
exception
Exceptio
n Object
catch block
Catches and
handles the
exception
try, throw, and catch blocks :
try {
// Set of Statments;
throw exception;
// Set of Statements;
catch(type arg)
{
// Set of Statements;
}
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-5
catch (object 1)
{
// catch section1
}
catch (object 2)
{
// catch section2
}
. . . . . . .
. . . . . . .
. . . . . . .
catch (type n object)
{
// catch section - n
}
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-5
#include<iostream>
using namespace std;
void num(int k)
{
try
{
if(k==0) throw k;
else
if(k>0) throw 'P';
else
if(k<0) throw .0;
cout<<"*** try block ***\n";
}
catch(...)
{
cout<<"Caught an exception \n";
}
}
int main()
{
cout<<"Demo of Multiple catches\n";
num(0);
num(5);
num(-1);
return 0;
}
here we have num class if k=0 we are going to throw null exception
if k>0 we are going to throw a character exception
if k<0 we are going to throw a double exception
II B.Tech-CSE-I Sem OOP THROUGH C++ :UNIT-5
Re-Throwing exception:
An exception is thrown from the catch block is known as the re-throwing exception.
We have seen a throw statement in try block, if we write throw statement in catch block then
it is called re-throwing exception.
It can be simply invoked by throw without arguments.
Rethrown exception will be caught by newly defined catch statement.
#include<iostream>
using namespace std;
void divide(double x, double y) {
try{
if(y==0)
throw y;
else
cout<<"Division= "<<x/y;
}
catch(double) {
cout<<"\nException inside function\n";
throw;
}
}
int main() {
try
{
divide(10.5,2.0);
divide(20.5,0.0);
}
catch(double)
{
cout<<"Exception inside main function";
}
return 0;
}
in main divide func is called with 2 args so it check y=0 if not it performs division operation.
next divide func is called with(20.5, 0.0) now y=0 ,it throws y as exception control will come to
catch block it displays Exception inside function and next stmt is throw and this throw stmt
throws exception to function call for that it needs catch block in main function and it gets
executed.