Module 5
Module 5
Module 5
• Oop in C++
Syllabus
• Class, object, Instantiation
• Inheritance
• Encapsulation
• Abstract class
• Polymorphism
• Constructors &destructors
• friend functions.
Introduction
• C++ is a general purpose case-sensitive language that supports object-oriented, procedural and
generic programming.
• C++ is a middle-level language, as it encapsulates both high and low level language features.
#include <iostream>
using namespace std;
int main() {
cout << "Hello C++ Programming";
return 0;
}
Usage of C++
By the help of C++ programming language, we can develop different types of secured and robust
applications:
1. Window application
2. Client-Server application
3. Device drivers
C++ is a simple language because it provides a structured approach (to break the problem
into parts), a rich set of library functions, data types, etc.
In C++, complex data types called Abstract Data Types (ADT) can be created using classes.
3) Portable
C++ is a portable language and programs made in it can be run on different machines.
4) Mid-level / Intermediate programming language
C++ includes both low-level programming and high-level language so it is known as a mid-level and
intermediate programming language. It is used to develop system applications such as kernel, driver, etc.
C++ is a structured programming language. In this we can divide the program into several parts using
functions.
6) Rich Library
C++ provides a lot of inbuilt functions that make the development fast. Following are the libraries used in
C++ provides very efficient management techniques. The various memory management operators help
save the memory and improve the program's efficiency. These operators allocate and deallocate
memory at run time. Some common memory management operators available C++ are new, delete etc.
8) Quicker Compilation
C++ programs tend to be compact and run quickly. Hence the compilation and execution time
C++ provides the feature of pointers. We can use pointers for memory, structures, functions, array, etc. We
10) Recursion
In C++, we can call the function within the function. It provides code reusability for every function.
11) Extensible
C++ programs can easily be extended as it is very easy to add new features into the existing program.
12) Object-Oriented
In C++, object-oriented concepts like data hiding, encapsulation, and data abstraction can easily be
implemented using keyword class, private, public, and protected access specifiers. Object-oriented makes
C++ is a compiler-based programming language, which means no C++ program can be executed
without compilation. C++ compiler is easily available, and it requires very little space for storage. First,
we need to compile our program using a compiler, and then we can execute our program.
14) Reusability
With the use of inheritance of functions programs written in C++ can be reused in any other program of
C++. You can save program parts into library files and invoke them in your next programming projects
simply by including the library files. New programs can be developed in lesser time as the existing code
can be reused. It is also possible to define several functions with same name that perform different task.
For Example: abs () is used to calculate the absolute value of integer, float and long integer.
C++ allows the programmer to redefine the meaning of existing operators such as +, -. For
Example, The "+" operator can be used for adding two numbers and concatenating two strings.
The programs written in C++ are well suited for real-world modeling problems as close as possible to
21) Clarity
The keywords and library functions used in C++ resemble common English words.
Object-Oriented Programming (OOPs)
• C++ supports the object-oriented programming, the four major pillar of object-oriented
programming (OOPs) used in C++ are:
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
I/O Library Header Files
Header File Function and Description
<iostream> It is used to define the cout, cin and
cerr objects, which correspond to standard
output stream, standard input stream and
standard error stream, respectively.
#include <iostream>
using namespace std;
int main( ) {
cout << “hello world" << endl;
}
Standard input stream (cin)
The cin is a predefined object of istream class. It is connected with the standard input device,
which is usually a keyboard. The cin is used in conjunction with stream extraction operator (>>)
#include <iostream>
using namespace std;
int main( )
{
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}
Standard end line (endl)
The endl is a predefined object of ostream class. It is used to insert a new line characters
#include <iostream>
using namespace std;
int main( )
{
cout << "C++";
cout << " Hello"<<endl;
cout << "End of line"<<endl;
}
There are 4 types of data types in C++ language.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Dynamic Binding - In dynamic binding, a decision is made at runtime regarding the code that
will be run in response to a function call. For this, C++ supports virtual functions.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. Data abstraction is the
process of exposing to the outside world only the information that is absolutely necessary while
concealing implementation or background information.For example: phone call, we don't know the
internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
Advantage of OOPs over Procedure-oriented programming language
2. OOPs provide data hiding whereas in Procedure-oriented programming language a global data
3. OOPs provide ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.
Class, object, Instantiation
C++ Object
• In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
• In other words, object is an entity that has state and behavior. Here, state means data and behavior
means functionality.
• Object is an instance of a class. All the members of the class can be accessed through object.
C++ Class
In C++, class is a group of similar objects. It is a template from which objects are created. It can have
fields, methods, constructors etc.
class Student
public:
};
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Sonoo Jaiswal";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
INHERITANCE
Inheritance
• The capability of a class to derive properties and characteristics from another class is
called Inheritance.
• Inheritance is a feature or a process in which, new classes are created from the existing
classes.
• The new class created is called “derived class” or “child class” and the existing class is
known as the “base class” or “parent class”.
• The derived class now is said to be inherited from the base class.
• When we say derived class inherits the base class, it means, the derived class
inherits all the properties of the base class, without changing the properties of base
class and may add new features to its own. These new features in the derived class
will not affect the base class. The derived class is the specialized class for the base
class.
• Sub Class: The class that inherits properties from another class is called Subclass
or Derived Class.
• Super Class: The class whose properties are inherited by a subclass is called Base
Class or Superclass.
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
};
Defining derived classes
• Syntax:
• Class derived_class_name : visibility_mode base_class_name
{
………………….
…………………..
…………………….
};
Why Encapsulation?
• It is considered good practice to declare your class attributes as private (as often
as you can). Encapsulation ensures better control of your data, because you (or
others) can change one part of the code without affecting other parts
• Increased security of data
•
Encapsulation
• The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from
users.
• To achieve this, you must declare class variables/attributes as private (cannot be
accessed from outside the class).
• If you want others to read or modify the value of a private member, you can
provide public get and set methods.
Data hiding:
Data hiding is an important aspect of encapsulation that enables the data members of a
class to be hidden from the clients of the class. By making the data members private and
enabling accessor and mutator functions to access and modify the data members, data
private:
// hidden data from outside world
int total;
};
C++ Polymorphism
• The term "Polymorphism" is the combination of "poly" + "morphs" which
means many forms. It is a Greek word. In object-oriented programming, we
use 3 main concepts: inheritance, encapsulation, and polymorphism.
There are two types of polymorphism in C++:
• Compile time polymorphism: The overloaded functions are invoked by matching the type and
number of arguments. This information is available at the compile time and, therefore, compiler
selects the appropriate function at the compile time.
• Run time polymorphism: Run time polymorphism is achieved when the object's method is
invoked at the run time instead of compile time. It is achieved by method overriding which is also
known as dynamic binding or late binding.
Differences b/w compile time and run time polymorphism.
#include<iostream>
using namespace std;
class Calculate
{
public: int main()
int add(int a,int b) {
{ Calculate c;
return a+b;
} cout<<c.add(20,23)<<endl;
int add(int a,int b,int d)
{ cout<<c.add(24,26,25);
return a+b+d;
} return 0;
}; }
C++ Operators Overloading
• It is an idea of giving special meaning to an existing operator in C++ without changing its original
meaning.
• In C++, we can make operators work for user-defined classes. This means C++ has the ability to
provide the operators with a special meaning for a data type, this ability is known as operator
overloading
• The advantage of Operators overloading is to perform different operations on the same operand.
#include<iostream>
#include<conio.h>
using namespace std;
class Test{
int main()
int a; {
public: Test t1,t2;
void get()
{ cout<<"enter first object value";
cin>>a; t1.get();
cout<<"enter second object value";
} t2.get();
void compare(Test t2) t1.compare(t2);
{ return 0;
if(a==t2.a) }
cout<<"objects are equal";
else
cout<<"objects are not equal";
};
#include<iostream>
#include<conio.h>
using namespace std;
class Test{
int a;
public:
void get()
{
cin>>a;
}
void operator==(Test t2)
{
if(a==t2.a)
cout<<"objects are equal";
else
cout<<"objects are not equal";
};
Can we overload all operators?
• sizeof
• Scope resolution (::)
• Class member access operators (.(dot), .* (pointer to member
operator))
• Ternary or conditional (?:)
Syntax of Operator Overloading
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
• Where the return type is the type of value returned by the function.
• operator op is an operator function where op is the operator being overloaded, and the
operator is the keyword.
Operators that can be overloaded Examples
Binary Arithmetic +, -, *, /, %
Unary Arithmetic +, -, ++, —
Assignment =, +=,*=, /=,-=, %=
Bitwise & , | , << , >> , ~ , ^
De-referencing (->)
Dynamic memory allocation,
New, delete
De-allocation
Subscript []
Function call ()
Logical &, | |, !
Relational >, < , = =, <=, >=
Overloading unary operator
• The unary operators operate on a single operand and following are the examples
of Unary operators −
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
• Here + is the binary operator that works on the operand num and 9
• When we overload the binary operator for user defined types by using the code:
The operator function is called using the obj1 object and obj2 is passed as an
argument to the function.
Overloading using friends
• Friend function using operator overloading offers better flexibility to the class.
• These functions are not a members of the class and they do not have 'this' pointer.
• When you overload a unary operator you have to pass one argument.
• When you overload a binary operator you have to pass two arguments.
• Syntax:
friend return-type operator operator-symbol (Variable 1, Varibale2)
{
//Statements;
}
#include<iostream>
using namespace std;
class Test{
int a,b;
friend void print(Test);
};
Friend function void print(Test t)
{
t.a=10;
t.b=20;
cout<<"a="<<t.a<<endl;
cout<<"b="<<t.b;
}
int main()
{
Test t;
print(t);
return 0;
}
#include<iostream>
using namespace std;
class Test2;
class Test1
{ void big(Test1 t1,Test2 t2)
int a;
{
public:
if(t1.a>t2.b)
void geta() cout<<"a is greater";
{ else
cout<<"enter the value of a"; cout<<"b is greater";
cin>>a; }
}
friend void big(Test1,Test2); int main()
};
{
class Test2
{ Test1 t1;
int b; Test2 t2;
public: t1.geta();
t2.getb();
void getb() big(t1,t2);
{ }
cout<<"enter the value of b";
cin>>b;
}
friend void big(Test1,Test2);
};
Type Conversion in C++
• Type conversion is the process that converts the predefined data type of one variable into
an appropriate data type.
• The main idea behind type conversion is to convert two different data type variables into
a single data type to solve mathematical and logical expressions easily without any data
loss.
• For example, we are adding two numbers, where one variable is of int type and another
of float type; we need to convert or typecast the int variable into a float to make them
both float data types to add them.
• Type conversion can be done in two ways
• Implicit type conversion
• Explicit type conversion
Implicit Type Conversion
• The implicit type conversion is the type of conversion done automatically by the compiler without
any human effort.
• It means an implicit conversion automatically converts one data type into another type based on
some predefined rules of the C++ compiler. Hence, it is also known as the automatic type
conversion.
Example :
int x = 20;
short int y = 5;
int z = x + y;
Order of the typecast in implicit conversion
bool -> char -> short int -> int -> unsigned int -> long int ->
unsigned long int -> long long int -> float ->
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
x = x + y;
float z = x + 1.1;
return 0;
}
Explicit type conversion
• Conversions that require user intervention to change the data type of one variable to another, is
called the explicit type conversion.
• In other words, an explicit conversion allows the programmer to manually changes or typecasts the
data type from one variable to another type. Hence, it is also known as typecasting.
• This is done by explicitly defining the required type in front of the expression in
parenthesis. This can be also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
return 0;
}
Output : Sum = 2
Conversion using Cast operator
(type conversion operators)
A Cast operator is an unary operator which forces one data type to be converted into another
data type.
C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
Static Cast
• This is the simplest type of cast which can be used. It not only performs upcasts, but also
downcasts. It is a compile time cast.
• Checks are not performed during the runtime to guarantee that an object being converted
is a full object of the destination type.
• Syntax:
#include<iostream>
using namespace std;
int main()
{
float a=10.5;
int b=static_cast<int>(a);
cout<<"a="<<a<<" "<<"b="<<b;
return 0;
}
Output
10
Hierarchical inheritance to get square and cube of
class Number {
private:
int num;
public:
void getNumber(void)
{
cout << "Enter an integer number: ";
cin >> num;
}
//to return num
int returnNumber(void)
{
return num;
}
};
class Square : public Number { class Cube : public Number {
public: private:
int getSquare(void) public:
{ int getCube(void)
int num, sqr; {
num = returnNumber(); //get number from class int num, cube;
Number num = returnNumber(); //get number from class Number
sqr = num * num; cube = num * num * num;
return sqr; return cube;
} }
}; };
int main()
{
Square objS;
Cube objC;
int sqr, cube;
objS.getNumber();
sqr = objS.getSquare();
cout << "Square of " << objS.returnNumber() << " is: " << sqr
<< endl;
objC.getNumber();
cube = objC.getCube();
cout << "Cube of " << objS.returnNumber() << " is: " << cube
<< endl;
return 0;
}
Output
#include <iostream>
#include <stdio.h>
using namespace std;
public:
void getLoanInfo(void)
{
getBasicInfo(); //to get basic info of an employee
cout << "Enter Loan Details: ";
cin.ignore(1);
cin.getline(loanDetails, 30);
cout << "Enter loan amount: ";
cin >> loanAmount;
}
void printLoanInfo(void)
{
cout << "Employee's Information is: " << endl;
cout << "Basic Information...:" << endl;
cout << "Name: " << name << endl; //accessing protected data
cout << "Employee ID: " << empId << endl; //accessing protected data
cout << "Gender: " << gender << endl
<< endl; //accessing protected data
cout << "Loan Information...:" << endl;
cout << "Loan Details: " << loanDetails << endl; //accessing protected data
cout << "Loan Amount : " << loanAmount << endl; //accessing protected data
}
};
int main()
{
//read and print department information
deptInfo objD;
objD.getDeptInfo();
objD.printDeptInfo();
objL.getLoanInfo();
objL.printLoanInfo();
return 0;
}