0% found this document useful (0 votes)
59 views65 pages

C++ Notes (Unit 1 To 5)

The document discusses the basic concepts of object-oriented programming in C++ including classes, objects, encapsulation, abstraction, polymorphism, inheritance, and dynamic binding. It then provides an overview of C++ programming and the structure of a basic C++ program including header files, namespaces, and the main function.

Uploaded by

parithi parithi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views65 pages

C++ Notes (Unit 1 To 5)

The document discusses the basic concepts of object-oriented programming in C++ including classes, objects, encapsulation, abstraction, polymorphism, inheritance, and dynamic binding. It then provides an overview of C++ programming and the structure of a basic C++ program including header files, namespaces, and the main function.

Uploaded by

parithi parithi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

OBJECT ORIENTED PROGRAMMING IN C++

OBJECT ORIENTED PROGRAMMING IN C++


UNIT I - INTRODUCTION TO C++
SYLLABUS

Principles of Object- Oriented Programming – Beginning with C++ - Tokens, Expressions and
Control Structures – Functions in C++.

1.1 OBJECT ORIENTED PROGRAMMING:

Object-oriented programming – As the name suggests uses objects in programming. Object-


oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc. in programming. The main aim of OOP is to bind together the data and
the functions that operate on them so that no other part of the code can access this data except
that function.

There are some basic concepts that act as the building blocks of OOPs i.e.

1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Dynamic Binding
8. Message Passing

1.1.1 CLASS:

1
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

• A Class is a user-defined data type that has data members and member functions.
• Data members are the data variables and member functions are the functions used
to manipulate these variables together these data members and member functions
define the properties and behavior of the objects in a Class.
1.1.2 OBJECT:

An Object is an identifiable entity with some characteristics and behavior. An Object is an


instance of a Class. When a class is defined, no memory is allocated but when it is instantiated
(i.e. an object is created) memory is allocated.

1.1.3 ENCAPSULATION

Encapsulation is defined as wrapping up data and information under a single unit. In Object-
Oriented Programming, Encapsulation is defined as binding together the data and the
functions that manipulate them.

1.1.4 ABSTRACTION:

Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and hiding
the details. Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation.

1.1.5 POLYMORPHISM:

The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A person at
the same time can have different characteristics.

C++ supports operator overloading and function overloading.

2
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

• Operator Overloading: The process of making an operator exhibit different


behaviors in different instances is known as operator overloading.
• Function Overloading: Function overloading is using a single function name to
perform different types of tasks. Polymorphism is extensively used in
implementing inheritance.
1.1.6 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.
• Sub Class: The class that inherits properties from another class is called Sub
class or Derived Class.
• Super Class: The class whose properties are inherited by a sub-class is called
Base Class or Superclass.
• Reusability: Inheritance supports the concept of “reusability”
1.1.7 DYNAMIC BINDING:

In dynamic binding, the code to be executed in response to the function call is decided at
runtime. C++ has virtual functions to support this.

1.1.8 MESSAGE PASSING:

Objects communicate with one another by sending and receiving information. A message for
an object is a request for the execution of a procedure and therefore will invoke a function in
the receiving object that generates the desired results.

1.2 C++ PROGRAMMING:

C++ is the most used and most popular programming language developed by Bjarne Stroustrup.
C++ is a high-level and object-oriented programming language. This language allows
developers to write clean and efficient code for large applications and software development,
game development, and operating system programming.

1.2.1 FEATURES OF C++:

C++ is a general-purpose programming language that was developed as an enhancement of


the C language to include an object-oriented paradigm. It is an imperative
and compiled language. C++ has a number of features, including:

3
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

• Object-Oriented Programming
• Machine Independent
• Simple
• High-Level Language
• Popular
• Case-sensitive
• Compiler Based
• Dynamic Memory Allocation
• Memory Management
• Multi-threading

1.3 HELLO WORLD IN C++:

The Hello World Program in C++ is the basic program that is used to demonstrate how the
coding process works.

#include <iostream.h>

int main()

// Prints hello world

cout << "Hello World";

return 0;

Output:

Hello World

Working of Hello World Program in C++

1. // C++ program to display “Hello World”

This line is a comment line. A comment is used to display additional information about the
program. A comment does not contain any programming logic.

2. #include

4
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

This is a preprocessor directive. The #include directive tells the compiler to include the
content of a file in the source code.

For example, #include<iostream> tells the compiler to include the standard iostream
file which contains declarations of all the standard input/output library functions.

3. int main() { }

A function is a group of statements that are designed to perform a specific task. The main()
function is the entry point of every C++ program, no matter where the function is located in
the program.

The opening braces ‘{‘ indicates the beginning of the main function and the closing braces
‘}’ indicates the ending of the main function.

4. cout<<“Hello World”;

std::cout is an instance of the std::ostream class, that is used to display output on the screen.
Everything followed by the character << in double quotes ” ” is displayed on the output
device. The semi-colon character at the end of the statement is used to indicate that the
statement is ending there.

5. return 0

This statement is used to return a value from a function and indicates the finishing of a
function. This statement is basically used in functions to return the results of the operations
performed by a function.

1.4 STRUCTURE OF C++:

5
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

The image above shows the basic C++ program that contains header files, main function,
namespace declaration, etc. Let’s try to understand them one by one.

1. Header File

The header files contain the definition of the functions and macros we are using in our
program. They are defined on the top of the C++ program.

In line #1, we used the #include <iostream> statement to tell the compiler to include
an iostream header file library which stores the definition of the cin and cout methods that
we have used for input and output. #include is a preprocessor directive using which we
import header files.

Syntax:

#include <library_name>

To know more about header files, please refer to the article – Header Files in C/C++.

2. Namespace

A namespace in C++ is used to provide a scope or a region where we define identifiers. It is


used to avoid name conflicts between two identifiers as only unique names can be used as
identifiers.

In line #2, we have used the using namespace std statement for specifying that we will be
the standard namespace where all the standard library functions are defined.

Syntax:

using namespace std;

3. Main Function

Functions are basic building blocks of a C++ program that contains the instructions for
performing some specific task. Apart from the instructions present in its body, a function
definition also contains information about its return type and parameters. To know more
about C++ functions, please refer to the article Functions in C++.

In line #3, we defined the main function as int main(). The main function is the most
important part of any C++ program. The program execution always starts from the main

6
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

function. All the other functions are called from the main function. In C++, the main function
is required to return some value indicating the execution status.

Syntax:

int main() {

... code ....

return 0;

4. Blocks

Blocks are the group of statements that are enclosed within { } braces. They define the scope
of the identifiers and are generally used to enclose the body of functions and control
statements.

The body of the main function is from line #4 to line #9 enclosed within { }.

Syntax:

// Body of the Function

return 0;

5. Semicolons

As you may have noticed by now, each statement in the above code is followed by a ( ; )
semicolon symbol. It is used to terminate each line of the statement of the program. When
the compiler sees this semicolon, it terminates the operation of that line and moves to the
next line.

Syntax:

7
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

any_statement ;

6. Identifiers

We use identifiers for the naming of variables, functions, and other user-defined data types.
An identifier may consist of uppercase and lowercase alphabetical characters, underscore,
and digits. The first letter must be an underscore or an alphabet.

Example:

int num1 = 24;

int num2 = 34;

num1 & num2 are the identifiers and int is the data type.

7. Keywords

In the C++ programming language, there are some reserved words that are used for some
special meaning in the C++ program. It can’t be used for identifiers.

For example, the words int, return, and using are some keywords used in our program.
These all have some predefined meaning in the C++ language.

There are total 95 keywords in C++. These are some keywords.

int void if while for auto bool break

this static new true false case char class

8. Basic Output cout

In line #7, we have used the cout method which is the basic output method in C++ to output
the sum of two numbers in the standard output stream (stdout).

Syntax:

cout << result << endl;

1.5 COMMENTS:

Comments in C++ are used to summarize an algorithm, identify a variable’s purpose, or clarify
a code segment that appears unclear.

Types of Comments in C++

8
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

• Single-line comment
• Multi-line comment

1. Single Line Comment


In C++ Single line comments are represented as // double forward slash. It applies comments
to a single line only. The compiler ignores any text after // and it will not be executed.
Syntax:
// Single line comment

2. Multi-Line Comment
A multi-line comment can occupy many lines of code, it starts with /* and ends with */, but it
cannot be nested. Any text between /* and */ will be ignored by the compiler.
Syntax:
/*
Multiline Comment
.
.
.
*/

1.6 TOKENS IN C++

Tokens can be defined as the smallest building block of C++ programs that the compiler
understands. The types of tokens in C++ are:

• Identifiers
• Keywords
• Constants
• Strings
• Special Symbols
• Operators

1.7 IDENTIFIERS:

In C++, entities like variables, functions, classes, or structs must be given unique names within
the program so that they can be uniquely identified. The unique names given to these entities
are known as identifiers.

9
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Rules for create identifiers:

An identifier can only begin with a letter or an underscore(_).

An identifier can consist of letters (A-Z or a-z), digits (0-9), and underscores (_). White
spaces and Special characters can not be used as the name of an identifier.

Keywords cannot be used as an identifier because they are reserved words to do specific tasks.
For example, string, int, class, struct, etc.

Identifier must be unique in its namespace.

1.8 KEYWORDS:

Keywords in C++ are the tokens that are the reserved words in programming languages that
have their specific meaning and functionalities within a program. Keywords cannot be used as
an identifier to name any variables.

For example, a variable or function cannot be named as ‘int’ because it is reserved for declaring
integer data type.

There are 95 keywords reserved in C++. Some of the main Keywords are:

break try catch char class const continue


default delete auto else friend for float
long new operator private protected public return
short sizeof static this typedef enum throw
mutable struct case register switch and or
namespace static_cast goto not xor bool do
double int unsigned void virtual union while

1.9 CONSTANTS:

Constants are the tokens in C++ that are used to define variables at the time of initialization
and the assigned value cannot be changed after that.

Syntax

const data_type variable_name = value;

Example:

10
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

const int n=4;

1.10 STRINGS:

A string is not a built-in data type like ‘int’, ‘char’, or ‘float’. It is a class available in the STL
library which provides the functionality to work with a sequence of characters, that represents
a string of text.

Syntax:

string variable_name;

Example:

String str= “Hello”;

1.11 SPECIAL SYMBOLS:

Special symbols are the token characters having specific meanings within the syntax of the
programming language.

• Semicolon (;): It is used to terminate the statement.


• Square brackets []: They are used to store array elements.
• Curly Braces {}: They are used to define blocks of code.
• Scope resolution (::): Scope resolution operator is used to access members of
namespaces, classes, etc.
• Dot (.): Dot operator also called member access operator used to access class and
struct members.
• Assignment operator ‘=’: This operator is used to assign values to variables.
• Double-quote (“): It is used to enclose string literals.
• Single-quote (‘): It is used to enclose character literals.

1.12 OPERATORS:

C++ operators are special symbols that are used to perform operations on operands such as
variables, constants, or expressions.

Types of Operators

11
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

• Unary Operators
• Binary Operators
• Ternary Operators
1. Unary Operators

Unary operators are used with single operands only. They perform the operations on a single
variable. For example, increment and decrement operators.

Increment operator ( ++ ): It is used to increment the value of an operand by 1.

Decrement operator ( — ): It is used to decrement the value of an operand by 1.

2. Binary Operators

They are used with the two operands and they perform the operations between the two
variables. For example (A<B), less than (<) operator compares A and B, returns true if A is
less than B else returns false.

Arithmetic Operators: These operators perform basic arithmetic operations on operands.


They include ‘+’, ‘-‘, ‘*’, ‘/’, and ‘%’

Comparison Operators: These operators are used to compare two operands and they include
‘==’, ‘!=’, ‘<‘, ‘>’, ‘<=’, and ‘>=’.

Logical Operators: These operators perform logical operations on boolean values. They
include ‘&&’, ‘||’, and ‘!‘.

Assignment Operators: These operators are used to assign values to variables and they
include ‘variables‘, ‘-=‘, ‘*=‘, ‘/=‘, and ‘%=’.

Bitwise Operators: These operators perform bitwise operations on integers. They include‘&’,
‘|’, ‘^’, ‘~’, ‘<<‘, and ‘>>‘.

3. Ternary Operator

The ternary operator is the only operator that takes three operands. It is also known as a
conditional operator that is used for conditional expressions.

Syntax:

Expression1 ? Expression2 : Expression3;

1.13 DIFFERENCE BETWEEN KEYWORD AND IDENTIFIERS:

12
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

SR. KEYWORD IDENTIFIER


NO.
1 Keywords are predefined word that Identifiers are the values used to define
gets reserved for working program different programming items such as
that have special meaning and variables, integers, structures, unions and
cannot get used anywhere else. others and mostly have an alphabetic
character.
2 Specify the type/kind of entity. Identify the name of a particular entity.
3 It always starts with a lowercase First character can be a uppercase,
letter. lowercase letter or underscore.
4 A keyword should be in lower case. An identifier can be in upper case or lower
case.
5 A keyword contains only An identifier can consist of alphabetical
alphabetical characters. characters, digits and underscores.
6 They help to identify a specific They help to locate the name of the entity
property that exists within a that gets defined along with a keyword.
computer language.
7 No special symbol, punctuation is No punctuation or special symbol except
used. ‘underscore’ is used.
8 Examples of keywords are: int, Examples of identifiers are: Test, count1,
char, if, while, do, class etc. high_speed, etc.

1.15 VARIABLES

Variables in C++ is a name given to a memory location. It is the basic unit of storage in a
program. The value stored in a variable can be changed during program execution.

Syntax:

type variable_name;

Example:

int a;

1.16 DATA TYPES:

The data types are used to tell the variables the type of data they can store.

13
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Types of data types:

1. Primary or Built-in or Fundamental data type


2. Derived data types
3. User-defined data types

1. Primitive Data Types: These data types are built-in or predefined data types and can be
used directly by the user to declare variables. example: int, char, float, bool, etc. Primitive
data types available in C++ are:
• Integer
• Character
• Boolean
• Floating Point
• Double Floating Point
• Valueless or Void
• Wide Character
2. Derived Data Types: Derived data types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types. These can be of four types namely:
• Function
• Array

14
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

• Pointer
• Reference
3. Abstract or User-Defined Data Types: Abstract or User-Defined data types are defined
by the user itself. Like, defining a class in C++ or a structure. C++ provides the following
user-defined datatypes:
• Class
• Structure
• Union
• Enumeration
• Typedef defined Datatype
1.17 INPUT AND OUTPUT IN C++

C++ comes with libraries that provide us with many ways for performing input and output.
In C++ input and output are performed in the form of a sequence of bytes or more commonly
known as streams.
• Input Stream: If the direction of flow of bytes is from the device(for example,
Keyboard) to the main memory then this process is called input.
• Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device( display screen ) then this process is called output.

CIN IN C++

The cin object in C++ is an object of class iostream. It is used to accept the input from the
standard input device i.e. keyboard.

COUT IN C++:

15
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

The cout object in C++ is an object of class iostream. It is defined in iostream header file. It
is used to display the output to the standard output device i.e. monitor.

Example:

#include <iostream>
using namespace std;

// Driver Code
int main()
{
string name;
int age;

// Take multiple input using cin


cin >> name >> age;

// Print output
cout << "Name : " << name << endl;
cout << "Age : " << age << endl;

return 0;
}
Output:

Siva

26

Name : Siva

Age : 26

1.18 CONDITIONAL STATEMENT:

The conditional statements (also known as decision control structures) such as if, if else,
switch, etc. are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not.

16
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

1.18.1 SIMPLE IF

The if statement is the simplest of the three and is used to run a certain piece of code nly if a
certain condition is true. For example:

int x = 5;
if (x == 5) {
cout << "x is 5" <<endl;
}

1.18.2 IF…ELSE

The if-else statement is used when we want to execute some code only if some condition exists.
If the given condition is true then code will be executed otherwise else statement will be used
to run other part of the code. For example:

int x = 5;
if (x == 5) {
cout << "x is 5" << endl;
} else {
cout << "x is not 5" << endl;
}

1.18.3 IF…ELSE..IF:

17
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";

1.18.4 SWITCH

The switch statement is used to execute different blocks of code based on the value of a
variable. For example:

int x = 2;
switch (x) {
case 1:
cout << "x is 1" << endl;
break;
case 2:
cout << "x is 2" <<endl;
break;
default:
cout << "x is not 1 or 2" <<endl;
break;
}

1.18.5 NESTED-IF

Nested if-else statements are those statements in which there is an if statement inside another
if else.

#include <iostream>
using namespace std;

int main()
{

18
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

// declaring three numbers


int a = 10;
int b = 2;
int c = 6;

// outermost if else
if (a < b) {
// nested if else
if (c < b) {
printf("%d is the greatest", b);
}
else {
printf("%d is the greatest", c);
}
}
else {
// nested if else
if (c < a) {
printf("%d is the greatest", a);
}
else {
printf("%d is the greatest", c);
}
}

return 0;
}

1.19 LOOPING STATEMENT:

There are three types of loops used in C++ programming:

1. for loop
2. while loop

19
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

3. do while loop

1.) for loop in C++

A for loop is a control structure that enables a set of instructions to get executed for a specified
number of iterations. It is an entry-controlled loop.

Syntax
for(initialization; testcondition; updateExpression)
{
//code to be executed
}
Example
// Program to print numbers from 1 to 10
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
cout << i << endl;
}
return 0;
}
Output

2.) Nested for loop in C++

It is any type of loop inside a for loop.

Example

#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
cout << j << " ";

20
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

}
cout << endl;
}
return 0;
}
Output
1
12
123
1234
12345

3.) Infinite for loop in C++

An infinite for loop gets created if the for loop condition remains true, or if the
programmer forgets to apply the test condition/terminating statement within the for loop
statement.

Syntax
for(; ;)
{
// body of the for loop.
}
In the above syntax, there is no condition hence, this loop will execute infinite times.

Example

#include <iostream>

int main() {
for (;;) {
std::cout << "Hello World" << std::endl;
}
return 0;
}

21
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

In the above code, we have run the for loop infinite times, so "Hello World" will be displayed
infinitely.

Output

Hello World
Hello World
Hello World
Hello World
Hello World
...

4.) for-each loop/ range-based for loop

This is a new kind of loop introduced in the C++11 version. It is used exclusively to
traverse through elements in an array and vector.

Syntax

for (variableName : arrayName/vectorName) {


// code block to be executed
}
Here, for every value in the array or vector, the for loop is executed and the value is assigned
to the variable.

Example

#include <iostream>
using namespace std;
int main() {
int num[7] = {10, 20, 30, 40, 50, 60, 70};
for (int i : num) {
cout << i << "\n";
}
return 0;
}

22
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Output

10
20
30
40
50
60
70
WHILE LOOPS:

A while loop evaluates the condition. If the condition evaluates to true, the code inside
the while loop is executed. The condition is evaluated again. This process continues until
the condition is false. When the condition evaluates to condition, the loop terminates.

While(condition){

//body of the loop

Example:

// C++ Program to print numbers from 1 to 5


#include <iostream.h>
using namespace std;
int main() {
int i = 1;
// while loop from 1 to 5
while (i <= 5) {
cout << i << " ";
++i;
}
return 0;
}
Output:

12345

23
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

DO… WHILE.. LOOP:

The do...while loop is a variant of the while loop with one important difference: the body
of do...while loop is executed once before the condition is checked.

Its syntax is:

do {
// body of loop;
}
while (condition);

Example:
#include <iostream.h>
using namespace std;
int main() {
int i = 1;
// do...while loop from 1 to 5
do {
cout << i << " ";
++i;
}
while (i <= 5);
return 0;
}
Output:
12345

24
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

UNIT II – CLASSES & CONSTRUCTORS


SYLLABUS

Classes and Objects – Constructors and Destructors – New Operator – Operator Overloading
and Type Conversions.

2.1 CLASS:

A Class is a user-defined data type that has data members and member functions.
Data members are the data variables and member functions are the functions used to
manipulate these variables together these data members and member functions define the
properties and behavior of the objects in a Class.
Syntax:

Example:
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};

2.2 OBJECT:

An Object is an identifiable entity with some characteristics and behavior. An Object is an


instance of a Class. When a class is defined, no memory is allocated but when it is instantiated
(i.e. an object is created) memory is allocated.

Syntax:

ClassName ObjectName;

25
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Example for Class and Object:


#include <iostream.h>
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;
}
Output:

201 Sonoo 990000

202 Nakul 29000

2.3 CONSTRUCTORS:

Constructors are special class members which are called by the compiler every time an object
of that class is instantiated. Constructors have the same name as the class and may be defined
inside or outside the class definition. There are 3 types of constructors:

• Default Constructors

• Parameterized Constructors

• Copy Constructors

Syntax:

Class_Name(list of parameters){

//constructor definition

26
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

2.3.1 C++ Default Constructor

A constructor which has no argument is known as default constructor. It is invoked at the time
of creating object.

Let's see the simple example of C++ default Constructor.

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}

Output:

Default Constructor Invoked

Default Constructor Invoked

2.3.2 C++ Parameterized Constructor

A constructor which has parameters is called parameterized constructor. It is used to provide


different values to distinct objects.

Let's see the simple example of C++ Parameterized Constructor.

#include <iostream.h>

27
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

using namespace std;


class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:

101 Sonoo 890000


102 Nakul 59000

2.3.3 Copy Constructor:

A copy constructor is a member function that initializes an object using another object of the
same class.

Syntax:

28
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Sample(Sample &t)
{
id=t.id;
}

2.4 DESTRUCTORS:

Destructor is another special member function that is called by the compiler when the scope of
the object ends.

Syntax

~ Class_Name()

Example for Constructor and destructor:

//Sum of Digits in a number using constructor and destructor


#include<iostream.h>
#include<conio.h>
class DigitSum
{
public:
DigitSum(int n)
{
int sum=0,n1;
n1=n;
while(n!=0)
{
sum=sum+(n%10);
n/=10;
}
cout<<"Sum of all digit of"<<n1<< "is "<<sum<<endl;
}

29
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

~DigitSum(){
cout<<"Destructor complete the program and free up memory";
}
};
void main()
{
int num;
clrscr();
cout<<"Enter number:";
cin>>num;
DigitSum(num);
getch();
}
Output:
Enter number: 1245
Sum of all digits of 1245 is 12
Destructor complete the program and free up memeory

2.5.1 NEW OPERATOR:

The “new” operator in C++ is used to allocate memory dynamically for a variable or an object
at runtime. This means that the memory is allocated during the execution of the program, as
opposed to being allocated at compile time.

Syntax:

Pointer_name=new datatype;

Or

pointer_variable = new datatype(value);

Example:

int *ptr=new int;

or

int *ptr=new int(10);

30
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Example:

#include <iostream>

int main() {

int* pInt = new int; // dynamically allocate memory for an int

*pnt = 5; // store the value 5 in the allocated memory

std::cout << *pnt; // output the value stored in the allocated memory

delete pnt; // deallocate the memory to prevent memory leak

return 0;

Output:

2.5.2 DELETE OPERATOR:

The delete operator is used to deallocate memory that was previously allocated on the heap
using new. It takes a pointer to the memory to be deallocated as an argument.

For example:

delete p; // Deallocates the memory pointed to by p

2.6 POLYMORPHISM:

The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A person at
the same time can have different characteristics.

31
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator overloading.
2.6.1 FUNCTION OVERLOADING:

Function overloading is using a single function name to perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Example:
#include <iostream.h>
using namespace std;
class Fun_overload {
public:
void func(int x)
{
cout << "value of x is " << x << endl;
}
void func(double x)
{
cout << "value of x is " << x << endl;
}
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
}
};
int main()
{
fun_overload obj1;
obj1.func(7);
obj1.func(9.132);
obj1.func(85, 64);
return 0;
}
Output:

32
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

value of x is 7
value of x is 9.132
value of x and y is 85, 64

2.6.2 OPERATOR OVERLOADING:

The process of making an operator exhibit different behaviors in different instances is known
as operator overloading.
Syntax:
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
Example:
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();

33
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

return 0;
}
Output:
The Count is: 10

2.7 TYPE CONVERSION:

Type conversion is the process that converts the predefined data type of one variable into an
appropriate data type. Type conversion can be done in two ways in C++

• Implicit type conversion


• Explicit type conversion

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

Order for implicit conversion is as follows

bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int -
> long long int -> float -> double -> long double

Program to convert int to float type using implicit type conversion

Program1.cpp

#include <iostream>
using namespace std;
int main ()
{
// assign the integer value
int num1 = 25;
// declare a float variable
float num2;
// convert int value into float variable using implicit conversion
num2 = num1;

34
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

cout << " The value of num1 is: " << num1 << endl;
cout << " The value of num2 is: " << num2 << endl;
return 0;
}
Output

The value of num1 is: 25


The value of num2 is: 25
2.7.2 Explicit conversion:
Conversions that require user intervention to change the data type of one variable to another,
is called the explicit type conversion.
Example:
#include <iostream>
using namespace std;
int main ()
{
float f2 = 6.7;
// use cast operator to convert data from one type to another
int x = static_cast <int> (f2);
cout << " The value of x is: " << x;
return 0;
}
Output:
The value of x is: 6

35
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

UNIT III – INHERITANCE


SYLLABUS

Extending Classes – Pointers- Virtual Functions and Polymorphism

3.1 EXTENDING CLASSES/ INHERITANCE:

Classes in C++ can be extended, creating new classes which retain characteristics of the base
class. This process, known as inheritance, involves a base class and a derived class:
The derived class inherits the members of the base class, on top of which it can add its own
members.

Types of Inheritance:

o Single inheritance

o Multiple inheritance

o Hierarchical inheritance

o Multilevel inheritance

o Hybrid inheritance

Derived Class:

A Derived class is defined as the class derived from the base class.

Syntax:

class derived_class_name :: visibility-mode base_class_name


{
// body of the derived class.
}
3.1.1 Single Inheritance:

Single inheritance is defined as the inheritance in which a derived class is inherited from the
only one base class.

36
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Where 'A' is the base class, and 'B' is the derived class.

Example:
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
Output:

Salary: 60000
Bonus: 5000

3.1.2 Multilevel Inheritance:

Multilevel inheritance is a process of deriving a class from another derived class.

37
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();

38
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

return 0;
}
Output:

Eating...
Barking...
Weeping...

3.1.3 Multiple Inheritance

Multiple inheritance is the process of deriving a new class that inherits the attributes from
two or more classes.

Syntax of the Derived class:

class D : visibility B-1, visibility B-2, ?


{
// Body of the class;
}
Example of multiple inheritance.
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}

39
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

};

class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
std::cout << "The value of a is : " <<a<< std::endl;
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();

return 0;
}
Output:

The value of a is : 10

40
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

The value of b is : 20
Addition of a and b is : 30

3.1.4 Hybrid Inheritance

Hybrid inheritance is a combination of more than one type of inheritance.

3.2 POINTERS:

The pointer in C++ language is a variable, it is also known as locator or indicator that points to
an address of a value.

The symbol of an address is represented by a pointer.

Syntax:

datatype *var_name;

int *ptr;

Symbols used in pointer

Symbol Name Description

& (ampersand sign) Address operator Determine the address of a variable.

∗ (asterisk sign) Indirection operator Access the value of an address.

41
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Declaring a pointer

The pointer in C++ language can be declared using ∗ (asterisk symbol).

int ∗ a; //pointer to int


char ∗ c; //pointer to char
Pointer Example

#include <iostream>
using namespace std;
int main()
{
int number=30;
int ∗ p;
p=&number;//stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}
Output:

Address of number variable is:0x7ffccc8724c4


Address of p variable is:0x7ffccc8724c4
Value of p variable is:30

3.3 VIRTUAL FUNCTIONS:

A C++ virtual function is a member function in the base class that you redefine in a derived
class. It is declared using the virtual keyword. It is used to tell the compiler to perform dynamic
linkage or late binding on the function.

#include <iostream>
{
public:
virtual void display()
{

42
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

cout << "Base class is invoked"<<endl;


}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
Output:
Derived Class is invoked

43
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

UNIT IV – FILES & TEMPLATES


SYLLABUS

Managing Console I/O Operations – Working with Files – Templates – Exception Handling.

4.1 CONSOLE I/O OPERATIONS:

Console input / output function take input from standard input devices and compute and give
output to standard output device. It is essential to know how to provide the input data and
present the results in the desired form.

Pre-defined Streams:

The pre-defined streams are also called as standard I/O objects. These streams are automatically
activated when program execution starts.

cin Standard input, usually keyboard, corresponding to stdin in C++. it handles input
from input devices usually from keyboard.
cout Standard output, usually screen, corresponding to stdout in C++. It passes data to
output devices such as monitors and printers. Thus, it controls output.
clog A fully buffered version of cerr. It controls stderr in C++ it controls error messages
that are passed from buffer to the standard error device.
cerr Standard error output, usually screen, corresponding to stderr in C++. It controls the
un-buffered output data. It catches the errors and passes to standard error device
monitor.
Example:

#include<iostream.h>
#include<conio.h>
int main(){
clrscr();
cout<< “\NSTREAMS”;
cerr<< “\NSTREAMS”;
clog<< “\NSTREAMS”;
return 0;
}
Output:
STREAMS

44
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

STREAMS
STREAMS
STREAM CLASSES:

C++ has number of classes that work with console and file operations. These classes are known
as stream classes.

There are two types of console I/O operations:

• Formatted console I/O Operations


• Unformatted console I/O Operations

1) Unformatted consol input output operations

These input / output operations are in unformatted mode. The following are operations of
unformatted consol input / output operations:

A) void get()

It is a method of cin object used to input a single character from keyboard. But

its main property is that it allows wide spaces and newline character.

Syntax:

char c=cin.get();

Example:

#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout<<c<<endl;
return 0;
}
Output
I
I
B) void put()

45
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

It is a method of cout object and it is used to print the specified character on the screen or
monitor.

Syntax:

cout.put(variable / character);

Example:

#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('c'); //Here it prints the character 'c';
return 0;
}
Output
I
Ic
C) getline(char *buffer,int size)

This is a method of cin object and it is used to input a string with multiple

spaces.

Syntax:

char x[30];

cin.getline(x,30);

Example:

#include<iostream>
using namespace std;
int main()
{
cout<<"Enter name :";

46
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout<<c<<endl;
return 0;
}
Output
Enter name :Divyanshu
Divyanshu

D) write(char * buffer, int n)

It is a method of cout object. This method is used to read n character from buffer variable.

Syntax:

cout.write(x,2);

Example:

#include<iostream>
using namespace std;
int main()
{
cout<<"Enter name : ";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout.write(c,9); //It reads only 9 character from
buffer c;
return 0;
}
Output
Enter name : Divyanshux
Divyanshu

E) cin:

It is the method to take input any variable / character / string.

Syntax:

47
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

cin>>variable / character / String / ;

Example:

#include<iostream>
using namespace std;
int main()
{
int num;
char ch;
string str;

cout<<"Enter Number"<<endl;
cin>>num; //Inputs a variable;
cout<<"Enter Character"<<endl;
cin>>ch; //Inputs a character;
cout<<"Enter String"<<endl;
cin>>str; //Inputs a string;

return 0;
}
Output
Enter Number
07
Enter Character
h
Enter String
Deepak

F) cout:

This method is used to print variable / string / character.

Syntax:

cout<< variable / charcter / string;

Example:

48
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

#include<iostream>
using namespace std;
int main()
{
int num=100;
char ch='X';
string str="Deepak";

cout<<"Number is "<<num<<endl; //Prints value of


variable;
cout<<"Character is "<<ch<<endl; //Prints character;
cout<<"String is "<<str<<endl; //Prints string;
return 0;
}
Output

Number is 100

Character is X

String is Deepak

2) Formatted console input output operations:

In formatted console input output operations we uses following functions to make output in
perfect alignment. In industrial programming all the output should be perfectly formatted due
to this reason C++ provides many function to convert any file into perfect aligned format. These
functions are available in header file <iomanip>. iomanip refers input output manipulations.

A) width(n)

This function is used to set width of the output.

Syntax:

cout<<setw(int n);

Example:

#include<iostream>

49
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

#include<iomanip>

using namespace std;

int main()

int x=10;

cout<<setw(20)<<variable;

return 0;

Output

10

B) fill(char)

This function is used to fill specified character at unused space.

Syntax:

cout<<setfill('character')<<variable;

Example:

#include<iostream>

#include<iomanip>

using namespace std;

int main()

int x=10;

cout<<setw(20);

cout<<setfill('#')<<x;

return 0;

50
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Output

##################10

D) precison(n)

This method is used for setting floating point of the output.

Syntax:

cout<<setprecision('int n')<<variable;

Example:

#include<iostream>

#include<iomanip>

using namespace std;

int main()

float x=10.12345;

cout<<setprecision(5)<<x;

return 0;

Output

10.123

E) setflag(arg 1, arg,2)

This function is used for setting format flags for output.

Syntax:

setiosflags(argument 1, argument 2);

F) unsetflag(arg 2)

51
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

This function is used to reset set flags for output.

Syntax:

resetiosflags(argument 2);

G) setbase(arg)

This function is used to set basefield of the flag.

Syntax:

setbase(argument);

4.2 FILES

To read and write from a file we are using the standard C++ library called fstream. Let us see
the data types define in fstream library is:

Data Type Description

fstream It is used to create files, write information to files, and read information from files.

ifstream It is used to read information from files.

ofstream It is used to create files and write information to the files.

4.2.1 CLASSES OF FILE STEAMS:

1. ios:-

52
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

ios stands for input output stream.

• This class is the base class for other classes in this class hierarchy.

• This class contains the necessary facilities that are used by all the other derived classes
for input and output operations.

2. istream:-

• istream stands for input stream.

• This class is derived from the class ‘ios’.

• This class handle input stream.

• The extraction operator(>>) is overloaded in this class to handle input streams from
files to the program execution.

• This class declares input functions such as get(), getline() and read().

3. ostream:-

• ostream stands for output stream.

• This class is derived from the class ‘ios’.

• This class handle output stream.

• The insertion operator(<<) is overloaded in this class to handle output streams to files
from the program execution.

• This class declares output functions such as put() and write().

4. streambuf:-

• This class contains a pointer which points to the buffer which is used to manage the
input and output streams.

5. fstreambase:-

• This class provides operations common to the file streams. Serves as a base for fstream,
ifstream and ofstream class.

• This class contains open() and close() function.

53
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

6. ifstream:-

• This class provides input operations.

• It contains open() function with default input mode.

• Inherits the functions get(), getline(), read(), seekg() and tellg() functions from the
istream.

7. ofstream:-

• This class provides output operations.

• It contains open() function with default output mode.

• Inherits the functions put(), write(), seekp() and tellp() functions from the ostream.

8. fstream:-

• This class provides support for simultaneous input and output operations.

• Inherits all the functions from istream and ostream classes through iostream.

9. filebuf:-

• Its purpose is to set the file buffers to read and write.

• We can also use file buffer member function to determine the length of the file.

4.2.2 C++ FileStream example: writing to a file:

Let's see the simple example of writing to a text file testout.txt using C++ FileStream
programming.

#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Welcome to javaTpoint.\n";

54
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

filestream << "C++ Tutorial.\n";


filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}
Output:

4.2.3 C++ FileStream example: reading from a file:

Let's see the simple example of reading from a text file testout.txt using C++ FileStream
programming.

#include <iostream>
#include <fstream>
using namespace std;
int main () {
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else {
cout << "File opening is fail."<<endl;
}
return 0;
}
Output:

Welcome to javaTpoint.

55
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

4.2.4 C++ Read and Write Example

Let's see the simple example of writing the data to a text file testout.txt and then reading the
data from the file using C++ FileStream programming.

#include <fstream>
#include <iostream>
using namespace std;
int main () {
char input[75];
ofstream os;
os.open("testout.txt");
cout <<"Writing to a text file:" << endl;
cout << "Please Enter your name: ";
cin.getline(input, 100);
os << input << endl;
cout << "Please Enter your age: ";
cin >> input;
cin.ignore();
os << input << endl;
os.close();
ifstream is;
string line;
is.open("testout.txt");
cout << "Reading from a text file:" << endl;
while (getline (is,line))
{
cout << line << endl;
}
is.close();
return 0;
}
Output:

Writing to a text file:

56
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Please Enter your name: Nakul Jain

Please Enter your age: 22

Reading from a text file: Nakul Jain

22

4.3 EXCEPTION HANDLING

In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters
during its execution. The process of handling these exceptions is called exception handling.

Types of C++ Exception

There are two types of exceptions in C++

1. Synchronous: Exceptions that happen when something goes wrong because of a


mistake in the input data or when the program is not equipped to handle the current type
of data it’s working with, such as dividing a number by zero.

2. Asynchronous: Exceptions that are beyond the program’s control, such as disc failure,
keyboard interrupts, etc.

C++ provides an inbuilt feature for Exception Handling. It can be done using the following
specialized keywords: try, catch, and throw with each having a different purpose.

Syntax of try-catch in C++

try {
// Code that might throw an exception
throw SomeExceptionType("Error message");
}
catch( ExceptionName e1 ) {
// catch block catches the exception that is thrown from try block
}
1. try in C++
The try keyword represents a block of code that may throw an exception placed inside the try
block. It’s followed by one or more catch blocks. If an exception occurs, try block throws that
exception.

57
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

2. catch in C++

The catch statement represents a block of code that is executed when a particular exception is
thrown from the try block. The code to handle the exception is written inside the catch block.

#include <iostream>
using namespace std;
float division(int x, int y) {
if( y == 0 ) {
throw "Attempted to divide by zero!";
}
return (x/y);
}
int main () {
int i = 25;
int j = 0;
float k = 0;
try {
k = division(i, j);
cout << k << endl;
}catch (const char* e) {
cerr << e << endl;
}
return 0;
}
Output:

Attempted to divide by zero!

3. throw in C++

An exception in C++ can be thrown using the throw keyword. When a program encounters a
throw statement, then it immediately terminates the current function and starts finding a
matching catch block to handle the thrown exception.

58
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

UNIT V – STL
SYLLABUS

Standard Template Library – Manipulating Strings – Object Oriented Systems Development.

5.1 STANDARD TEMPLATE LIBRARY:

The Standard Template Library (STL) is a set of C++ template classes to provide common
programming data structures and functions such as lists, stacks, arrays, etc.

The C++ Standard Template Library (STL) is a collection of algorithms, data structures, and
other components that can be used to simplify the development of C++ programs.

STL has 4 components:

• Algorithms

• Containers

• Functors

• Iterators

5.1.1 Algorithms

The header algorithm defines a collection of functions specially designed to be used on a range
of elements. They act on containers and provide means for various operations for the contents
of the containers.

• Algorithm

• Sorting

• Searching

• Important STL Algorithms

• Useful Array algorithms

• Partition Operations

• Numeric

• valarray class

5.1.2 Containers

59
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

Containers or container classes store objects and data. There are in total seven standards “first-
class” container classes and three container adaptor classes and only seven header files that
provide access to these containers or container adaptors.

• Sequence Containers: implement data structures that can be accessed in a sequential


manner.

• vector

• list

• deque

• arrays

• forward_list( Introduced in C++11)

• Container Adaptors: provide a different interface for sequential containers.

• queue

• priority_queue

• stack

• Associative Containers: implement sorted data structures that can be quickly searched
(O(log n) complexity).

• set

• multiset

• map

• multimap

• Unordered Associative Containers: implement unordered data structures that can be


quickly searched

• unordered_set (Introduced in C++11)

• unordered_multiset (Introduced in C++11)

• unordered_map (Introduced in C++11)

• unordered_multimap (Introduced in C++11)

60
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

5.1.3 Functors

The STL includes classes that overload the function call operator. Instances of such classes are
called function objects or functors. Functors allow the working of the associated function to be
customized with the help of parameters to be passed. Must Read – Functors

5.1.4 Iterators

As the name suggests, iterators are used for working on a sequence of values. They are the
major feature that allows generality in STL. Must Read – Iterators

5.2 STRING MANIPULATIONS:

C++ strings are sequences of characters stored in a char array. Strings are used to store words
and text. They are also used to store data, such as numbers and other types of information.
Strings in C++ can be defined either using the std::string class or the C-style character arrays.

5.2.1 C Style String:

These strings are stored as the plain old array of characters terminated by a null character ‘\0’.
They are the type of strings that C++ inherited from C language.

Syntax:

char str[] = "GeeksforGeeks";

Example:

#include <iostream>
using namespace std;
int main()
{
char s1[] = { 'g', 'f', 'g', '\0' };
char s2[4] = { 'g', 'f', 'g', '\0' };
char s3[4] = "gfg";
char s4[] = "gfg";
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
cout << "s4 = " << s4 << endl;

61
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

return 0;
}
Output:

s1 = gfg
s2 = gfg
s3 = gfg
s4 = gfg

5.2.2 String Keyword:

These are the new types of strings that are introduced in C++ as std::string class defined inside
<string> header file. This provides many advantages over conventional C-style strings such as
dynamic size, member functions, etc.

Syntax:

string str("GeeksforGeeks");

Exampl:
#include <iostream>
using namespace std;

int main()
{
string s = "GeeksforGeeks";
string str("GeeksforGeeks");
cout << "s = " << s << endl;
cout << "str = " << str << endl;
return 0;
}
Output:

s = GeeksforGeeks

str = GeeksforGeeks

String Input:

62
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

String input means accepting a string from a user. In C++. We have different types of taking
input from the user which depend on the string. The most common way is to take input
with cin keyword with the extraction operator (>>) in C++. Methods to take a string as input
are:

• cin

• getline

• stringstream

5.3 OBJECT ORIENTED SYSTEM DEVELOPMENT:

Object Oriented System is a type of development model where Objects are used to specify
different aspects of an Application. Everything including Data, information, processes,
functions, and so on is considered an object in Object-Oriented System.

5.3.1 PHASES OF OBJECT-ORIENTED SOFTWARE DEVELOPMENT

Object-Oriented Development is a structured approach to design and build software systems


using the principle of Object-Oriented Programming(OOP).

5.3.2 Object-Oriented Analysis

Object-Oriented Analysis (OOA) is the initial Phase in Software Development that focuses on
the Understanding User Requirement in terms of Objects. OOA is the important phase in
Software Development that help in understanding, organizing and defining the problem or
system before moving into the designing Part and Implementation Part.

63
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

5.3.3 Object-Oriented Design

Object Oriented Design is a Key phase in Software Development followed by Object Oriented
Analysis. OOD is a process of creating a well-structured and Organized Design for a Software
System based on Object Oriented.

Object Oriented Design includes both:

• System Design

• Object Design

5.3.4 System Design

System Design is critical part in Object Oriented Design where we design a Software System
based on the information gathered during Analysis of the requirement of the Software. System
Design focuses on the roadmap that provides how various components and modules of the
software will work together. Designing a system is done according to both Analysis and the
purposed Architecture of system

5.3.5 Object Design

Object Design is critical part of Object Oriented Design where the main focus is on the detailed
design of individual Classes and Objects, Specifying how they are Implemented on the System
design of Software Development. Object Design is the foundation of writing Actual Code for
the Software Development and it must be ensured that system is efficient, easily maintainable
and extensible.

5.3.6 Object-Oriented Implementation

• Object Oriented Implementation is a Phase in Software Development where the design


model and the Structure that is developed in Object Oriented Analysis and Object
oriented Design is translated into actual Code using Appropriate Programming
Language.

class Book:

def __init__(self, title, author, available=True):

self.title = title

self.author = author

64
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++

self.available = available

#Some Book objects

book1 = Book("XYZ", "Ashutosh", True)

book2 = Book("Yzx", "Amit", False)

5.3.7 Object Oriented Testing

Object Oriented Testing is the last Phase in Software Development that focus on Verify and
Validating the functionality of Software System. This phase verify the Actual Code and
Performance of Object Oriented System, it uses specialized techniques to identify and remove
the errors in the Code. Object Oriented Testing encompasses various levels of testing which
Includes unit testing, integration testing, system testing and so on. Object Oriented Testing
ensures reliability and quality of Object Oriented Software System.

65
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC

You might also like