C++ Notes (Unit 1 To 5)
C++ Notes (Unit 1 To 5)
Principles of Object- Oriented Programming – Beginning with C++ - Tokens, Expressions and
Control Structures – Functions in C++.
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:
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.
2
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
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.
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.
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.
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
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()
return 0;
Output:
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.
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
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:
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() {
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:
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:
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.
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:
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.
8
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
• Single-line comment
• Multi-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
.
.
.
*/
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++
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.
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:
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
Example:
10
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
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:
Special symbols are the token characters having specific meanings within the syntax of the
programming language.
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.
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.
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:
12
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
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;
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++
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;
// Print output
cout << "Name : " << name << endl;
cout << "Age : " << age << endl;
return 0;
}
Output:
Siva
26
Name : Siva
Age : 26
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++
// 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. 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
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
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
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
...
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
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){
Example:
12345
23
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
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.
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++
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:
Syntax:
ClassName ObjectName;
25
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
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++
A constructor which has no argument is known as default constructor. It is invoked at the time
of creating object.
#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:
#include <iostream.h>
27
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
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()
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
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
Example:
or
30
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
Example:
#include <iostream>
int main() {
std::cout << *pnt; // output the value stored in the allocated memory
return 0;
Output:
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:
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
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
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++
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.
bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int -
> long long int -> float -> double -> long double
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
35
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
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:
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
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...
Multiple inheritance is the process of deriving a new class that inherits the attributes from
two or more classes.
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.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.
Syntax:
datatype *var_name;
int *ptr;
41
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
Declaring a pointer
#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:
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++
43
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
Managing Console I/O Operations – Working with Files – Templates – Exception Handling.
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.
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
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:
Syntax:
47
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
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:
Syntax:
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";
Number is 100
Character is X
String is Deepak
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)
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>
int main()
int x=10;
cout<<setw(20)<<variable;
return 0;
Output
10
B) fill(char)
Syntax:
cout<<setfill('character')<<variable;
Example:
#include<iostream>
#include<iomanip>
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)
Syntax:
cout<<setprecision('int n')<<variable;
Example:
#include<iostream>
#include<iomanip>
int main()
float x=10.12345;
cout<<setprecision(5)<<x;
return 0;
Output
10.123
E) setflag(arg 1, arg,2)
Syntax:
F) unsetflag(arg 2)
51
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
Syntax:
resetiosflags(argument 2);
G) setbase(arg)
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:
fstream It is used to create files, write information to files, and read information from files.
1. ios:-
52
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
• 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:-
• 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:-
• The insertion operator(<<) is overloaded in this class to handle output streams to files
from the program execution.
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.
53
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
6. ifstream:-
• Inherits the functions get(), getline(), read(), seekg() and tellg() functions from the
istream.
7. ofstream:-
• 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:-
• We can also use file buffer member function to determine the length of the 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++
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++
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:
56
Mr.B.Sivabharathi, Asst.Prof, Dept of CS & AI, ESASC
OBJECT ORIENTED PROGRAMMING IN C++
22
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.
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.
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:
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
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.
• 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
• 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.
• vector
• list
• deque
• arrays
• queue
• priority_queue
• stack
• Associative Containers: implement sorted data structures that can be quickly searched
(O(log n) complexity).
• set
• multiset
• map
• multimap
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
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.
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:
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
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
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.
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++
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.
• System Design
• Object 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
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.
class Book:
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
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