Module 5 Final

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 76

Module 5

Syllabus • Oop in C++

• Class, object, Instantiation

• Inheritance

• Encapsulation

• Abstract class

• Polymorphism

• Overloading Virtual functions

• 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

4. Embedded firmware etc


Features

1) Simple

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.

2) Abstract Data types

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.

5) Structured programming language

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++

programming are:
7) Memory Management

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 of the C+

+ language is fast.
9) Pointer

C++ provides the feature of pointers. We can use pointers for memory, structures, functions, array, etc. We can directly

interact with the memory by using the pointers.

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 development and maintenance

easier.
3) Compiler based

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.

15) National Standards

C++ has national standards such as ANSI.


16) Errors are easily detected
It is easier to maintain a C++ programs as errors can be easily located and rectified. It also provides a feature
called exception handling to support error handling in your program.
17) Power and Flexibility
C++ is a powerful and flexible language because of most of the powerful flexible and modern UNIX operating
system is written in C++. Many compilers and interpreters for other languages such as FORTRAN, PERL,
Python, PASCAL, BASIC, LISP, etc., have been written in C++. C++ programs have been used for solving
physics and engineering problems and even for animated special effects for movies.
18) Strongly typed language
The list of arguments of every function call is typed checked during compilation. If there is a type mismatch
between actual and formal arguments, implicit conversion is applied if possible. A compile-time occurs if an
implicit conversion is not possible or if the number of arguments is incorrect.
16) Errors are easily detected
It is easier to maintain a C++ programs as errors can be easily located and rectified. It also provides a feature
called exception handling to support error handling in your program.
17) Power and Flexibility
C++ is a powerful and flexible language because of most of the powerful flexible and modern UNIX operating
system is written in C++. Many compilers and interpreters for other languages such as FORTRAN, PERL,
Python, PASCAL, BASIC, LISP, etc., have been written in C++. C++ programs have been used for solving
physics and engineering problems and even for animated special effects for movies.
18) Strongly typed language
The list of arguments of every function call is typed checked during compilation. If there is a type mismatch
between actual and formal arguments, implicit conversion is applied if possible. A compile-time occurs if an
implicit conversion is not possible or if the number of arguments is incorrect.
19) Redefine Existing Operators

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.

20) Modelling real-world problems

The programs written in C++ are well suited for real-world modeling problems as close as possible to the user

perspective.

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.

<fstream> It is used to declare services for user-controlled file


processing.
Standard output stream (cout)
• The cout is a predefined object of ostream class. It is connected with the standard output device,
which is usually a display screen. The cout is used in conjunction with stream insertion operator
(<<) to display the output on a console

#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 (>>) to read the input

from a console.

#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 and flushes

the stream.

#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.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure


Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical

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

1. OOPs makes development and maintenance easier where as in Procedure-oriented programming language

it is not easy to manage if code grows as project size grows.

2. OOPs provide data hiding whereas in Procedure-oriented programming language a global data can be

accessed from anywhere.

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 a runtime entity, it is created at runtime.

• 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:

int id; //field or data member

float salary; //field or data member

String name;//field or data member

};
#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 one of the most important features of Object-Oriented Programming.

• 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 hiding can be accomplished.
#include <iostream>
using namespace std;
class Adder {
public:
// constructor int main() {
Adder(int i = 0) { Adder a;
total = i;
} a.addNum(10);
a.addNum(20);
// interface to outside world a.addNum(30);
void addNum(int number) {
total += number; cout << "Total " << a.getTotal()
} <<endl;
return 0;
// interface to outside world }
int getTotal() {
return total;
};

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.

Compile time polymorphism Run time polymorphism


The function to be invoked is known at the The function to be invoked is known at the run
compile time. time.
It is also known as overloading, early binding It is also known as overriding, Dynamic binding
and static binding. and late binding.
Overloading is a compile time polymorphism Overriding is a run time polymorphism where
where more than one method is having the same more than one method is having the same name,
name but with the different number of parameters number of parameters and the type of the
or the type of the parameters. parameters.
It is achieved by function overloading and It is achieved by virtual functions and pointers.
operator overloading.
It provides fast execution as it is known at the It provides slow execution as it is known at the
compile time. run time.
It is less flexible as mainly all the things execute It is more flexible as all the things execute at the
at the compile time. run time.
Types of overloading in C++ are:
Function overloading
Operator overloading
FUNCTION OVERLOADING

#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?

Following is the list of operators that cannot be overloaded.

• 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.

• class_name is the name of the class.

• 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 −

• The increment (++) and decrement (--) operators.

• The unary minus (-) operator.

• The logical not (!) operator.


#include<iostream>
using namespace std; int main()
class Test{ {
int a;
public:
Test t;
Test(){ ++t;
a=0; t.show();
} ++t;
void operator ++() t.show();
{
a++;
--t;
} t.show();
void operator --() return 0;
{ }
a--;
}
void show()
{
cout<<a<<endl;
}
};
#include <iostream>
using namespace std;

class Complex {
private:
int real, imag;

public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}

Complex operator+(Complex obj)


{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
Overloading binary operators
• Binary operators work on two operands.

For example, Result=num+9;

• 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:

Obj 3= obj 1+ obj 2;

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.

• Friend function can access private members of a class directly.

• 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 ->

double -> long double


#include <iostream>
using namespace std;

int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97

x = x + y;

// x is implicitly converted to float

float z = x + 1.1;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

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.

• The explicit type conversion is divided into two ways:

1. Explicit conversion using the cast operator

2. Explicit conversion using the assignment operator


Converting by assignment:

• 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;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}

Output : Sum = 2
Hierarchical inheritance to get square and cube of a number program in C++
#include <iostream>
using namespace std;

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

Enter Name: Mickey


Enter Emp. Id: 1121
Enter Gender: F Enter Name: Mickey
Enter Department Name: Testing Enter Emp. Id: 1121
Enter assigned work: To test login form Enter Gender: F
Enter time in hours to complete work: 20 Enter Loan Details: HOME LOAN
Employee's Information is: Enter loan amount: 150000
Basic Information...: Employee's Information is:
Name: Mickey Basic Information...:
Employee ID: 1121 Name: Mickey
Gender: F Employee ID: 1121
Gender: F
Department Information...:
Department Name: Testing Loan Information...:
Assigned Work: To test login form Loan Details: HOME LOAN
Time to complete work: 20 Loan Amount : 150000
/*
C++ program to read and print employee information with department
and pf information using hierarchical inheritance.
*/

#include <iostream>
#include <stdio.h>
using namespace std;

//Base Class - basicInfo


class basicInfo {
protected:
char name[30];
int empId;
char gender;
public:
void getBasicInfo(void)
{
cout << "Enter Name: ";
public:
cin.ignore(1);
void getDeptInfo(void)
cin.getline(name, 30);
{
cout << "Enter Emp. Id: ";
getBasicInfo(); //to get basic info of an employee
cin >> empId;
cout << "Enter Department Name: ";
cout << "Enter Gender: ";
cin.ignore(1);
cin >> gender;
cin.getline(deptName, 30);
}
cout << "Enter assigned work: ";
};
fflush(stdin);
cin.getline(assignedWork, 30);
//Base Class - deptInfo
cout << "Enter time in hours to complete work: ";
class deptInfo : private basicInfo {
cin >> time2complete;
protected:
}
char deptName[30];
char assignedWork[30];
int time2complete;
void printDeptInfo(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 << "Department Information...:" << endl;


cout << "Department Name: " << deptName << endl; //accessing protected data
cout << "Assigned Work: " << assignedWork << endl; //accessing protected data
cout << "Time to complete work: " << time2complete << endl; //accessing protected data
}
};
//another Base Class : loadInfo
class loanInfo : private basicInfo {
protected:
char loanDetails[30];
int loanAmount;

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();

cout << endl


<< endl;
//read and print loan information
loanInfo objL;

objL.getLoanInfo();
objL.printLoanInfo();

return 0;
}

You might also like