C++ Notes
C++ Notes
RECOMMENDED BOOKS:
1. Object Oriented Programming : McGregor and Sykes S A, 1992 Van Nostrand.
2. The C++ Programming Language : Strustrp B,Addision Wasley.
3. Object Oriented Programming in C++ : Lafore R, Galgotia Publications.
4. Introduction to Object Oriented Programming : Witt KV, Galgotia Publications.
5. Object Oriented Programming : Blaschek G, Springer Verlag
6. Object Data Management : Cattel R, Addison Wasley.
The first high-level programming languages were designed in the 1950s. Now there are dozens of different languages,
including Ada, Algol, BASIC, COBOL, C, C++, JAVA, FORTRAN, LISP, Pascal, and Prolog. Such languages are considered
high-level because they are closer to human languages and farther from machine languages. In contrast, assembly
languages are considered low- level because they are very close to machine languages.
In the procedure oriented approach, the problem is viewed as sequence of things to be done such as reading,
calculation and printing.
Procedure oriented programming basically consist of writing a list of instruction or actions for the computer to
follow and organizing these instruction into groups known as functions.
“Object oriented programming as an approach that provides a way of modularizing programs by creating partitioned
memory area for both data and functions that can be used as templates for creating copies of such modules on
demand”.
Objects
Classes
Data abstraction
Data encapsulation
Inheritance
Polymorphism
Dynamic binding
Message passing
OBJECTS
Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the
program must handle.
The fundamental idea behind object oriented approach is to combine both data
and function into a single unit and these units are called objects.
The term objects means a combination of data and program that represent some
real word entity. For example: consider an example named Amit; Amit is 25 years
old and his salary is 2500. The Amit may be represented in a computer program as
an object. The data part of the object would be (name: Amit, age: 25, salary: 2500)
The program part of the object may be collection of programs (retrieve of data, change age, change of salary).
In general even any user –defined type-such as employee may be used. In the Amit object the name, age and
salary are called attributes of the object.
CLASS:
A class in C++ is the building block that leads to Object-Oriented programming. It is a user-defined data type,
which holds its own data members and member functions, which can be accessed and used by creating an
instance of that class. A C++ class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of
them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc.
So here, Car is the class and wheels, speed limits, mileage are their properties.
Data Abstraction
Data Abstraction is a process of providing only the essential details to the outside world and hiding the internal
details, i.e., representing only the essential details in the program.
Data Abstraction is a programming technique that depends on the separation of the interface and
implementation details of the program.
C++ provides a great level of abstraction. For example, pow() function is used to calculate the power of a
number without knowing the algorithm the function follows.
In C++ program if we implement class with private and public members then it is an example of data
abstraction.
Data Encapsulation
The wrapping up of data and function into a single unit
(called class) is known as encapsulation. The data is not
accessible to the outside world and only those functions
which are wrapped in the class can access it. These
functions provide the interface between the objects data
and the program.
Inheritance:
Inheritance is the process by which objects of one class
acquire the properties of another class. In the concept of
inheritance provides the idea of reusability. This means
that we can add additional features to an existing class
without modifying it. This is possible by designing a new
class will have the combined features of both the classes.
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.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to the executed in response to the call. Dynamic
binding means the code associated with a given procedure call is not known until the time of the call at run-
time. It is associated with a polymorphic reference depends upon the dynamic type of that reference.
Message Passing
An object oriented program consists of a set of objects that
communicate with each other.
A message for an object is a request for execution of a
procedure and therefore will invoke a function (procedure)
in the receiving object that generates the desired result.
Message passing involves specifying the name of the
object, the name of the function (message) and
information to be sent.
Benefits of OOP
OOPs offer several benefits to both the program designer and the user. Object-oriented contributes to the
solution of many problems associated with the development and quality of software products. The principal
advantages are:
Through inheritance we can eliminate redundant code and extend the use of existing classes.
We can build programs from the standard working modules that communicate with one another,
rather than having to start writing the code from scratch. This leads to saving of development time
and higher productivity.
This principle of data hiding helps the programmer to build secure programs that can’t be invaded by
code in other parts of the program.
It is possible to have multiple instances of an object to co-exist without any interference.
It is easy to partition the work in a project based on objects.
Object-oriented systems can be easily upgraded from small to large systems.
Message passing techniques for communication between objects makes the interface description
with external systems much simpler.
Software complexity can be easily managed.
Application of OOP
The most popular application of oops up to now, has been in the area of user interface design such as
windows. There are hundreds of windowing systems developed using OOP techniques.
Real business systems are often much more complex and contain many more objects with complicated
attributes and methods. OOP is useful in this type of applications because it can simplify a complex problem.
The promising areas for application of OOP include.
Real – Time systems.
Simulation and modeling
Object oriented databases.
Hypertext, hypermedia and expertext.
Al and expert systems.
Neural networks and parallel programming.
Decision support and office automation systems.
CIM / CAM / CAD system.
Overview of C++
C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that
supports procedural, object-oriented, and generic programming.
C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level
language features.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as an
enhancement to the C language and originally named C with Classes but later it was renamed C++ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.
Data-type
All variables use data-type during declaration to restrict the type of data to be stored. Therefore, we can say
that data types are used to tell the variables the type of data it can store. Whenever a variable is defined in
C++, the compiler allocates some memory for that variable based on the data-type with which it is declared.
Every data type requires a different amount of memory.
A constant value in C++ is an explicit number or character (such as 1, 0.5, or ‘c’) that doesn’t change. As with
variables, every constant has a type. In an expression such as n = 1; the constant value 1 is an int. To make 1 a
long integer, write the statement as n = 1L;
Operators
The operators are the special type of functions that takes one or more parameters and gives new result. It is a
symbol that tells the compiler to perform the mathematical and logical manipulations. The programming
language like C or C++ is incomplete without the use of operators.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Bitwise operators
Arithmetic Operators
The arithmetic operators are used to perform the arithmetic operations on the operands. The operations can
be addition, multiplication, subtraction and division.
Relational Operators
The relational operators are those operators that are used to compare the values of two operands. For
example, by comparing two operands that their values are equal or not, or the value of one operand is greater
than the other.
Logical Operators
The logical operators are those operators that are used to combine two or more conditions. The logical
operators are AND (&&) and OR (||). If we combine two statements using AND operator then only both the
valid statements will be considered and if we combine two statements using OR operator then only either one
of them will be considered.
Assignment Operators
The assignment operators are those operators which are used to assign value to a variable. On the left side of
the assignment operator the operand is a variable and the right side of the operator the operand is a value.
The value on the right side of the operator should be of the same data type as of variable on the left side of
the operator otherwise it will show a compile error.
Bitwise Operators
The bitwise operators are those are used to perform bit level operations on the operands. In the bitwise
operators first operators are converted to bit level and then calculation is performed on the operands. Some
of the operations which are performed are addition, subtraction, multiplication, division, etc.
Expressions
An expression is a sequence of operators and the operands. It is a form when you combine operands and
operators.
Arithmetic Expression
An arithmetic expression is that expression in which arithmetic operators are used. Like addition,
multiplication, subtraction, division, etc.
Relational Expression
A relational expression is that expression in which relational operators are used. The operators provided in
relational expression are less than (<), greater than (>), less than equal to (<=), greater than equal to (>=), etc.
Logical Expression
A logical expression is that expression in which logical operators are used. Some of the logical operators are
AND (&&), OR (||), NOT (!).
Control Structures
A program is nothing but the execution of sequence of one or more instructions.
Quite often, it is desirable to alter the sequence of the statements in the program depending upon certain
circumstances. (i.e., we have a number of situations where we may have to change the order of execution of
statements based on certain conditions) Or Repeat a group of statements until certain specified conditions are
met.
This involves a kind of decision making to see whether a particular condition has occurred or not and direct the
computer to execute certain statements accordingly.
Based on application, it is necessary / essential
These statements change the flow of execution depending on a given logical condition. Used to execute or skip
some set of instructions based on given condition.
“if” statement is a powerful decision making statement, and is used to control the flow of execution of
statements. It is basically a “Two-way” decision statement (one for TRUE and other for FALSE) It has only one
option. The statement as executed only when the condition is true. In case the condition is false the compiler
skips the lines within the “if Block”.
Syntax:
if (Condition or test expression)
{
Statement;
}
Rest of the program;
Syntax :
if ( Test Expression or Condition )
{
Statements; /*true block (or) if block */
}
else
{
Statements; /* false block (or) else block */
}
Using of one if-else statement in another if-else statement is called as nested if-else control statement.
When a series of decisions are involved, we may have to use more than one if-else statement in nested form.
Syntax:
if ( Test Condition1)
{
if ( Test Condition2)
{
Statement -1;
}
else
{
Statement -2;
}
}
else
{
if ( Test Condition3)
{
Statement -3;
}
else
{
Statement-4;
}
} /* end of outer if-else *
If Test Condition-1 is true then enter into outer if block, and it checks Test Condition2,if it is true then
Statement-1 executed if it is false then else block executed i.eStatement-2.
If Test Condition -1 is false then it skips the outer if block and it goes to else block and Test Condition-3 checks
if it is true then Statement-3 executed, else Statement-4 executed.
This is another way of putting if‘s together when multiple decisions are involved. A multipath decision is a
chain of if‘s in which the statement associated with each else is an if. Hence it forms a ladder called else–if
ladder.
if else-if, statement is used to execute one code from multiple conditions.
Syntax:
else
{
default statement;
}
Rest of the Program Statements-X;
Switch is another conditional control statement used to select one option from several options based on given
expression value; this is an alternative to the if-else-if ladder. The switch statement causes a particular group
of statements to be chosen from several available groups. The selection is based upon the current value of an
expression which is included with in the switch statement. The switch statement is a multi-way branch
statement.
In a program if there is a possibility to make a choice from a number of options, this structured selected is
useful. The switch statement requires only one argument of int or char data type, which is checked with
number of case options. The switch statement evaluates expression and then looks for its value among the
case constants. If the value matches with case constant, then that particular case statement is executed.
If no one case constant not matched then default is executed.
Here switch, case and default are reserved words or keywords. Every case statement terminates with colon
“:”. In switch each case block should end with break statement, i.e.
Syntax:
Switch (variable or expression)
{
Case Constantvalue-1: Block -1;
(Or)
Statement-1;
break;
_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
Loop: A loop is defined as a block of statements which are repeatedly executed for certain number of times.
In other words it iterates a code or group of code many times.
Why use loops in c language: Suppose you want to execute some code/s 10 times. You can perform it by
writing that code/s only one time and repeat the execution 10 times using loop. For example: Suppose that
you have to print table of 2 then you need to write 10 lines of code, by using loop statements you can do it by
2 or 3 lines of code only.
The for loop works well where the number of iterations of the loop is
known before the loop is entered. The head of the loop consists of
three parts separated by semicolons.
The first is run before the loop is entered. This is usually the
initialization of the loop variable.
The second is a test, the loop is exits when this returns false.
The third is a statement to be run every time the loop body is
completed. This is usually an increment of the loop counter.
The 3 actions are
“Initialize expression”, “Test Condition expression” and “updation expression”
The expressions are separated by Semi-Colons (;).
Syntax:
for (initialize expression; test condition; updation )
{
Statement-1;
Statement-2;
}
The initialization sets a loop to an initial value. This statement is executed only once.
The test condition is a relational expression that determines the number of iterations desired or it
determines when to exit from the loop.
For loop continues to execute as long as conditional test is satisfied.
When the condition becomes false the control of the program exits from the body of for loop and executes
next statements after the body of the loop.
The updation (increment or decrement operations) decides how to make changes in the loop.
The body of the loop may contain either a single statement or multiple statements.
Syntax:
Jump-statement;
break;
The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.
In “while” and “do” loops continue causes the control to go directly to the test –condition and then to
continue the iteration process. In the case of “for” loop, the updation section of the loop is executed before
test-condition, is evaluated.
Syntax:
Jump-statement;
Continue;
The jump statement can be while, do while and for loop.
C supports the “goto” statement to branch unconditionally from one point to another in the program.
Although it may not be essential to use the “goto” statement in a highly structured language like “C”, there
may be occasions when the use of goto is necessary. The goto requires a label in order to identify the place
where the branch is to be made.
A label is any valid variable name and must be followed by a colon (: ). The label is placed immediately before
the statement where the control is to be transferred. The label can be anywhere in the program either before
or after the goto label statement.
Syntax:
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto statement, the control of the
program will jump to the label: and executes the code below it.
String
One of the most useful data types supplied in the C++ libraries is the string. A string is a variable that stores a
sequence of letters or other characters, such as "Hello" or "May 10th is my birthday!” Just like the other data
types, to create a string we first declare it, then we can store a value in it.
Storage Class
Storage Classes are used to describe the features of a variable/function. These features basically include the
scope, visibility and life-time which help us to trace the existence of a particular variable during the runtime of
a program. To specify the storage class for a variable, the following syntax is to be followed:
Syntax:
storage_class var_data_type var_name;
1. Structure in C++
In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for
lightweight objects such as Rectangle, color, Point, etc.
Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended
to be modified after creation of struct.
C++ Structure is a collection of different data types. It is similar to the class that holds different types of data.
Student s;
Here, s is a structure variable of type Student. When the structure variable is created, the memory will be
allocated. Student structure contains one char variable and two integer variable. Therefore, the memory for
one char variable is 1 byte and two ints will be 2*4 = 8. The total memory occupied by the s variable is 9 byte.
The variable of the structure can be accessed by simply using the instance of the structure followed by the dot
(.) operator and then the field of the structure.
For example:
s.id = 4;
In the above statement, we are accessing the id field of the structure Student by using the dot (.) operator and
assigns the value 4 to the id field.
Enumeration in C++
Enum in C++ is a data type that contains fixed set of constants. It can be used for days of the week (SUNDAY,
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and
WEST) etc. The C++ enum constants are static and final implicitly.
C++ Enums can be thought of as classes that have fixed set of constants.
2. Functions in C++
The function in C++ language is also known as procedure or subroutine in other programming languages.
To perform any task, we can create function. A function can be called many times. It provides modularity and
code reusability.
Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the same code again and
again.
Code optimization
It makes the code optimized; we don't need to write much code.
Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or not. Without using
function, you need to write the prime number logic 3 times. So, there is repetition of code. But if you use
functions, you need to write the logic only once and you can reuse it several times.
Types of Functions
Library Functions: are the functions which are declared in the C++ header files such as ceil(x), cos(x), exp(x),
etc.
User-defined functions: are the functions which are created by the C++ programmer, so that he/she can use it
many times. It reduces complexity of a big program and optimizes the code.
Defining a Function
The general form of a C++ function definition is as follows −
A C++ function definition consists of a function header and a function body. Here are all the parts of a function
Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the parameter list together
constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no
parameters.
Function Body − The function body contains a collection of statements that define what the function does.
Declaration of a function
A function declaration tells the compiler about a function name and how to call the function. The actual body
of the function can be defined separately.
For the above defined function max(), following is the function declaration −
Parameter names are not important in function declaration only their type is required, so following is also valid
declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that function in
another file. In such case, you should declare the function at the top of the file calling the function.
Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use a function, you will
have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called function
performs defined task and when it’s return statement is executed or when its function-ending closing brace is
reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function
returns a value, then you can store returned value.
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry into
the function and destroyed upon exit.
There are two ways to pass value or data to function in C language: call by value and call by reference. Original
value is not modified in call by value but it is modified in call by reference.
In call by value, value being passed to the function is locally stored by the function parameter in stack memory
location. If you change the value of function parameter, it is changed for the current function only. It will not
change the value of variable inside the caller method such as main ().
Here, address of the value is passed in the function, so actual and formal arguments share the same address
space. Hence, value changed inside the function, is reflected inside as well as outside the function.
Note: To understand the call by reference, you must have the basic knowledge of pointers.
1 A copy of value is passed to the function An address of value is passed to the function
Changes made inside the function is not Changes made inside the function is reflected
2
reflected on other functions outside the function also
Actual and formal arguments will be created Actual and formal arguments will be created in
3
in different memory location same memory location
Overloaded Function
C++ allows specification of more than one function of the same name in the same scope. These functions are
called overloaded functions. Overloaded functions enable you to supply different semantics for a function,
depending on the types and number of arguments.
Inline Function
If make a function as inline, then the compiler replaces the function calling location with the definition of the
inline function at compile time.
To inline a function, place the keyword inline before the function name and define the function before any
calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more
than a line.
Any changes made to an inline function will require the inline function to be recompiled again because the
compiler would need to replace all the code with a new code; otherwise, it will execute the old functionality.
Let's understand the difference between the normal function and the inline function.
Inside the main() method, when the function fun1() is called, the control is transferred to the definition of the
called function. The addresses from where the function is called and the definition of the function are
different. This control transfer takes a lot of time and increases the overhead.
When the inline function is encountered, then the definition of the function is copied to it. In this case, there is
no control transfer which saves a lot of time and also decreases the overhead.
Definition
A default argument is a value in the function declaration automatically assigned by the compiler if the calling
function does not pass any value to that argument.
The values passed in the default arguments are not constant. These values can be overwritten if the value is
passed to the function. If not, the previously declared value retains.
During the calling of function, the values are copied from left to right.
All the values that will be given default value will be on the right.
Example
Return Statement
Terminates the execution of a function and returns control to the calling function (or to the operating system if you
transfer control from the main function). Execution resumes in the calling function at the point immediately
following the call.
Syntax
return [expression];
Returning by Reference
Pointers and References in C++ held close relation with one another. The major difference is that the pointers
can be operated on like adding values whereas references are just an alias for another variable.
dataType& functionName(parameters);
Where,
dataType is the return type of the function,
and parameters are the passed arguments to it.
3. Array in C++
C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the
highest address to the last element.
Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and the number of elements
required by an array as follows –
This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type
can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use
this statement −
double balance[10];
Initializing Arrays
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we declare for
the array between square brackets [ ]. Following is an example to assign a single element of the array –
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you
write −
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th,
i.e., last element because all arrays have 0 as the index of their first element which is also called base index.
Following is the pictorial representation of the same array we discussed above –
Arrays in C++
Arrays are important to C++ and should need lots of more detail. There are following few important concepts,
which should be clear to a C++ programmer −
Multi-dimensional arrays
C++ supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional
array.
Pointer to an array
You can generate a pointer to the first element of an array by simply specifying the array name, without any
index.
Multi-dimensional arrays
C++ allows multidimensional arrays. Here is the general form of a multidimensional array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −
int threedim[5][10][4];
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in
essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y, you would
write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y number of columns. A
2-dimensional array a, which contains three rows and four columns can be shown as below –
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of
the array, and i and j are the subscripts that uniquely identify each element in a.
If you want to pass a single-dimension array as an argument in a function, you would have to declare function
formal parameter in one of following three ways and all three declaration methods produce similar results
because each tells the compiler that an integer pointer is going to be received.
Now, consider the following function, which will take an array as an argument along with another argument
and based on the passed arguments, it will return average of the numbers passed through the array
C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other words, object is an
entity that has state and behavior. Here, state means data and behavior means functionality. Object is a runtime
entity, it is created at runtime. Object is an instance of a class. All the members of the class can be accessed
through object.
Let's see an example to create object of student class using s1 as the reference variable.
Student s1; //creating an object of Student
In this example, Student is the type and s1 is the reference variable that refers to the instance of Student class.
C++ Class
In C++, class is a group of similar objects. It is a template from which objects are created. It can have fields,
methods, constructors etc.
Let's see an example of C++ class that has three fields only.
class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name; //field or data member
}
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 = "ICECDS";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
class Student
{
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
int main(void)
{
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert (201, "ICE");
s2.insert (202, "CDS");
s1.display ();
s2.display ();
return 0;
}
class Employee
{
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
void insert(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
e1.insert (201, "ICE", 25000);
e2.insert (202, "CDS", 29000);
e1.display ();
e2.display ();
return 0;
}
C++ Constructor
In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to
initialize the data members of new object generally. The constructor in C++ has the same name as class or
structure.
There can be two types of constructors in C++.
Default constructor
Parameterized constructor
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
class Employee
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee (101, "ICE", 25000); //creating an object of Employee
Employee e2=Employee (102, "CDS", 59000);
e1.display ();
e2.display ();
return 0;
}
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only once in a
class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde sign (~).
Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.
Example - C++ Constructor and Destructor
class Employee
{
public:
Employee ()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee ()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
As we know that, we can pass any type of arguments within the member function and there are any numbers of
arguments.
In C++ programming language, we can also pass an object as an argument within the member function of class.
This is useful, when we want to initialize all data members of an object with another object, we can pass objects
and assign the values of supplied object to the current object. For complex or large projects, we need to use
objects as an argument or parameter.
Example - Object as Function Arguments
class Demo
{
private:
int a;
public:
void set(int x)
{
a = x;
}
void sum(Demo ob1, Demo ob2)
{
a = ob1.a + ob2.a;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
}
};
int main()
{
Demo d1; //object declarations
Demo d2; //object declarations
Demo d3; //object declarations
d1.set (10); //assigning values to the data member of objects
d2.set (20); //assigning values to the data member of objects
d3.sum (d1, d2); //passing object d1 and d2
d1.print (); //printing the values
d2.print (); //printing the values
d3.print (); //printing the values
return 0;
}
Usage It is used for smaller amounts of data. It is used for a huge amount of data.
Requires
It may have only parameterized It may have all the types of constructors
constructor and
constructor. and destructors.
destructor
#include<iostream>
const int size=5;
class student
{
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
} ;
ICECDS MSc CS -Sai College Bhilai 31
OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam
int main()
{
student stu;
stu.getdata() ;
stu.tot_marks() ;
return 0;
}
OUTPUT
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2: 54
Enter marks in subject 3: 68
Enter marks in subject 4: 72
Enter marks in subject 5: 82
Total marks = 343
In this example, an array marks is declared as a private member of the class student for storing a
student’s marks in five subjects. The member function tot_marks () calculates the total marks of all the subjects
and displays the value.
Similar to other data members of a class, the memory space for an array is allocated when an object of
the class is declared. In addition, different objects of the class have their own copy of the array. Note that the
elements of the array occupy contiguous memory locations along with other data members of the object. For
instance, when an object stu of the class student is declared, the memory space is allocated for both rollno and
marks
Operators Overloading
You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use
operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the
operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
Operator Overloading provide a flexible option for the creation of new definition for most of the C++ operators
Defining Operator Overloading
return_type class_name:: operator op (argument)
{
function body;
}
#include<iostream.h>
#include<conio.h>
class space
{
int x,y,z ;
public:
void getdata(int a,int b,int c);
void display(void);
void Operator - ();
};
{
cout<<x;
cout<<y;
cout<<z;
}
void space::Operator -()
{
x=-x;
y=-y;
z=-z;
}
void main()
{
space s;
s.getdata (10,-20, 30);
cout<<"s:";
s.display ();
-s; // activate Operator - ()
cout<<"s:";
s.display ();
}
#include<iostream.h>
#include<conio.h>
class complex
{
float x; // Real
float y; // imaginary
public:
complex () //construct
complex (float real, float image)
{
x=real;
y=image;
}
complex operator +(complex);
void display(void);
};
complex complex ::operator + (complex c)
{
complex temp;
temp.x = x+c.x;
temp.y = y+c.y;
return (temp);
}
void complex::display(void)
{
cout<<x<<"+j"<<y<<"\n";
}
void main()
{
clrscr();
complex c1,c2,c3;
cout<<"c1 = ";
c1.display ();
cout<<"c2 = ";
c2.display ();
cout<<"c3 = ";
c3.display ();
getch();
}
Method Overloading
If we inherit a class into the derived class and provide a definition for one of the base class function again inside
the derived class then that is said to be override and the mechanism is called function overriding.
Requirement of Overriding a Function/Method
Inheritance should there function overriding cannot alone within a class for these we required a
derived class and base class
Function that is redefine must have exactly the same declaration in both base and derived class that
means same name, same return type and same parameter list
Example - Binary Operators Overloading
class Base
{
public:
void show() // Method Overriding
{
cout<<"Base Class";
}
};
void main()
{
Base b; // Base Class Object
Derived d; // Derived Class Object
b.show(); // Early Binding Occur
d.show(); // Early Binding Occur
getch();
}
In the above example we are calling the overriding function using Base class and Derived Class objects. Base class
object will call base version of the function and Derived class object will call derived version of the function.
class Base
{
public:
void show() // Method Overriding
{
cout<<"Base Class";
}
};
{
cout<<"Derivrd Class";
}
};
void main()
{
Base *b; // Base Class Object
Derived d; // Derived Class Object
b=&d;
dshow(); // Early Binding Occur
getch();
}
In this example although the object of derived class still base class method is called this happens due to early
binding compiler on seeing base class pointer set called to base class show() function without knowing the actual
class
Inheritance
The capability of a class to derive properties and characteristics from another class is called Inheritance.
Inheritance is one of the most important feature 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 sub class is called Base Class or Super class.
You can clearly see that above process results in duplication of same code 3 times. This increases the chances of
error and data redundancy. To avoid this type of situation, inheritance is used. If we create a class Vehicle and
write these three functions in it and inherit the rest of the classes from the vehicle class, then we can simply avoid
the duplication of data and increase re-usability. Look at the below diagram in which the three classes are
inherited from vehicle class.
Then we can simply avoid the duplication of data and increase reusability.
Using inheritance, we have to write the functions only one time instead of three times as we have inherited rest
of the three classes from base class (Vehicle).
Implementing inheritance in C++: For creating a sub-class which is inherited from the base class we have to follow
the below syntax.
Syntax:
Class subclass_name: access_mode base_class_name
{
//body of subclass
};
Subclass_name is the name of the sub class,
Access_mode is the mode in which you want to inherit this sub class for example: public, private etc.
Base_class_name is the name of the base class from which you want to inherit the sub class.
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent object,
which contains any private members which that class declares.
class Parent
{
public:
int id_p;
};
class Child : public Parent // Sub class inheriting from Base Class(Parent)
{
public:
int id_c;
};
int main()
{
return 0;
}
In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data members of
the class ‘Parent’ will also be inherited by the class ‘Child’.
Modes of Inheritance
Public mode: If we derive a sub class from a public base class. Then the public member of the base class
will become public in the derived class and protected members of the base class will become protected
in derived class.
Protected mode: If we derive a sub class from a Protected base class. Then both public member and
protected members of the base class will become protected in derived class.
Private mode: If we derive a sub class from a Private base class. Then both public member and protected
members of the base class will become Private in derived class.
ICECDS MSc CS -Sai College Bhilai 38
OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam
Note: The private members in the base class cannot be directly accessed in the derived class, while protected
members can be directly accessed.
Implementation to show that the derived class does not inherit access to private data member it does inherit the
full parent object
class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class
is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
Example
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
int main()
{
Car obj; OUTPUT
getch();
This is a Vehicle
return 0;
} Objects with 4 wheels are
vehicles
Multiple Inheritance: Multiple Inheritance is a feature of C++has
Car where
4 aWheels
class can inherit from more than
one classes. i.e one sub class is inherited from more than one base classes.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2,……
{
//body of subclass
};
Example
class Vehicle // first base class
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
int main()
{ OUTPUT
Car obj;
getch(); This is a Vehicle
return 0;
This is a 4 wheeler
}
Vehicle
Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived class.
Example
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" <<
endl;
}
};
Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a single
base class. i.e. more than one derived class is created from a single base class.
Example
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
int main()
{ OUTPUT
Car obj1;
Bus obj2; This is a Vehicle
getch(); This is a Vehicle
return 0;
}
Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type of
inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
Example
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
class Fare
{
public:
Fare()
{
cout<<"Fare of Vehicle\n";
}
};
OUTPUT
This is a Vehicle
Fare of Vehicle
Example
class ClassA
{
public:
int a;
};
obj.b = 20;
obj.c = 30;
obj.d = 40;
In the above example, both ClassB & ClassC inherit ClassA, they both have single copy of ClassA. However ClassD inherit
both ClassB & ClassC, therefore ClassD have two copies of ClassA, one from ClassB and another from ClassC.
If we need to access the data member of ClassA through the object of ClassD, we must specify the path from which a
will be accessed, whether it is from ClassB or ClassC, because compiler can’t differentiate between two copies of ClassA
in ClassD.
There are 2 ways to avoid this ambiguity:
1. Scope resolution operator 2. Virtual Base Class – Unit 5
Here we can manually specify the path from which data member a will be accessed.
Pointers
Pointers are symbolic representation of addresses. They enable programs to simulate call-by-reference as well as
to create and manipulate dynamic data structures. Its general declaration in C++ has the format:
Syntax:
datatype *var_name;
int *ptr; //ptr can point to an address which holds int data
Pointer to Void
In C++, we cannot assign the address of a variable of one data type to a pointer of another data type.
Example
// pointer is of int type
int *ptr;
// Error
// can't assign double* to int*
ptr = &d;
Here, the error occurred because the address is a double type variable. However, the pointer is of int type.
In such situations, we can use the pointer to void (void pointers)
Example
void *ptr;
double d = 9.0;
ptr = &d;
The void pointer is a generic pointer that is used when we don't know the data type of the variable that the pointer
points to.
Example
#include <iostream>
int main()
{
void* ptr;
float f = 2.3f;
ptr = &f;
This program prints the value of the address pointed to by the void pointer ptr.
Since we cannot dereference a void pointer, we cannot use *ptr.
However, if we convert the void* pointer type to the float* type, we can use the value pointed to by the void pointer.
In this example, we have used the static_cast operator to convert the data type of the pointer from void* to float*.
Note: void pointers cannot be used to store addresses of variables with const or volatile qualifiers.
void *ptr;
const double d = 9.0;
ptr = &d; // Error: invalid conversion from const void* to void*
Here, ptr is a pointer variable while arr is an int array. The code ptr = arr; stores the address of the first element of
the array in variable ptr.
Notice that we have used arr instead of &arr[0]. This is because both are the same. So, the code below is the same
as the code above.
int *ptr;
int arr[5];
ptr = &arr[0];
The addresses for the rest of the array elements are given by &arr[1], &arr[2], &arr[3], and &arr[4].
In the above example, since p stores the address of name[0], therefore the value of *p equals the value of name[0]
i.e., 'S'. So in while loop, the first character gets printed and p++ increases the value of p by 1 so that now p+1
points to name[1]. This continues until the pointer reaches the end of the string i.e., before *p becomes equal to
'\0'.
cout << "Length of " << name << " = " << len1 << endl;
cout << "Length of " << "Hello World" << " = " << len2 << endl;
return 0;
}
New Operator
The new operator allocates memory to a variable. For example,
Here, we have dynamically allocated memory for an int variable using the new operator.
Notice that we have used the pointer pointVar to allocate the memory dynamically. This is because the new
operator returns the address of the memory location.
In the case of an array, the new operator returns the address of the first element of the array.
From the example above, we can see that the syntax for using the new operator is
pointerVariable = new dataType;
Delete Operator
Once we no longer need to use a variable that we have declared dynamically, we can deallocate the memory
occupied by the variable.
For this, the delete operator is used. It returns the memory to the operating system. This is known as memory
deallocation.
Syntax
delete pointerVariable;
Here, we have dynamically allocated memory for an int variable using the pointer pointVar. After printing the
contents of pointVar, we deallocated the memory using delete.
Example
#include<iostream.h>
int main()
{
clrscr()
int *point 1;
float *point 2;
* point 1 = 100;
* point 2 = 98.32;
cout<< * point 1;
cout<< * point 2;
delete point 1;
delete point 2;
getch();
return 0;
}
void getAge()
{
cout << "Age = " << age << endl;
}
};
int main()
{
Student* ptr = new Student (); // dynamically declare Student object
PtrgetAge (); // call getAge () function
delete ptr; // ptr memory is released
return 0;
}
In this program, we have created a Student class that has a private variable age.
We have initialized age to 12 in the default constructor Student () and print its value with the function getAge ().
In main (), we have created a Student object using the new operator and use the pointer ptr to point to its address.
The moment the object is created, the Student () constructor initializes age to 12.
We then call the getAge () function using the code:
PtrgetAge ();
Notice the arrow operator. This operator is used to access class members using pointers.
The above diagram shows the memory representation of a pointer to pointer. The first pointer ptr1 stores the
address of the variable and the second pointer ptr2 stores the address of the first pointer.
Example
int main()
{
int var = 789;
return 0; OUTPUT
} Value of var = 789
Value of var using single pointer = 789
Value of var using double pointer = 789
Pointers to Objects
You can access an object either directly, or by using a pointer to the object.
To access an element of an object when using the actual object itself, use the dot operator.
To access a specific element of an object when using a pointer to the object, you must use the arrow () operator.
Example
#include<iostream.h>
class myclss
{
int i
public:
void read (int j)
{
i=j;
}
int getint()
{
return i;
}
};
void main()
{
clrscr();
myclss ob *op;
getch();
}
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.
There is a necessity to use the single pointer to refer to all the objects of the different classes. So, we create
the pointer to the base class that refers to all the derived objects. But, when base class pointer contains the
address of the derived class object, always executes the base class function. This issue can only be resolved
by using the 'virtual' function.
A 'virtual' is a keyword preceding the normal declaration of a function.
When the function is made virtual, C++ determines which function is to be invoked at the runtime based on
the type of the object pointed by the base class pointer.
Example:
#include <iostream>
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
std::cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{
Base *bptr; //Base b; OUTPUT
Derived d; Derived class is derived from the base
class.
bptr = &d;
bptr->show();
return 0;
}
In the above example, the base class contains the pure virtual function. Therefore, the base class is an abstract
base class. We cannot create the object of the base class.
Early Binding (compile-time time polymorphism) As the name indicates, compiler (or linker) directly associate
an address to the function call. It replaces the call with a machine language instruction that tells the mainframe
to leap to the address of the function.
By default early binding happens in C++. Late binding (discussed below) is achieved with the help of virtual
keyword)
Example
#include<iostream.h>
class Base
{
public:
void show()
{
cout<<" In Base \n";
}
};
class Derived: public Base
{
public:
void show()
{
cout<<"In Derived \n";
}
};
int main(void)
{
Base *bp = new Derived;
// The function call decided at
// compile time (compiler sees type
// of pointer and calls base class
// function.
bp->show();
return 0; Output
} In Base
Late Binding: (Run time polymorphism) In this, the compiler adds code that identifies the kind of object at
runtime then matches the call with the right function definition (Refer this for details). This can be achieved by
declaring a virtual function.
Example
#include<iostream>
class Base
{
public:
virtual void show()
{
cout<<" In Base \n";
}
};
int main(void)
{
Base *bp = new Derived; Output
bp->show(); // RUN-TIME POLYMORPHISM In Derived
return 0;
}
Friend function
If a function is defined as a friend function in C++, then the protected and private data of a class can be accessed
using the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a class starting with
the keyword friend.
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};
In the above declaration, the friend function is preceded by the keyword friend. The function can be defined
anywhere in the program like a normal C++ function. The function definition does not use either the keyword friend
or scope resolution operator.
The function is not in the scope of the class to which it has been declared as a friend.
It cannot be called using the object as it is not in the scope of that class.
It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an object name and dot membership operator
with the member name.
It can be declared either in the private or the public part.
int printLength(Box b)
{
b.length += 10;
return b.length;
Output
}
Length of box: 10
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
Friend class
Friend Class A friend class can access private and protected members of other class in which it is declared as friend.
It is sometimes useful to allow a particular class to access private members of other class.
For example, a Linked List class may be allowed to access private members of Node.
class Node
{
private:
int key;
Node* next;
/* Other members of Node Class */
// Now class LinkedList can
// access private members of Node
friend class LinkedList;
};
Friend Function Like friend class, a friend function can be given a special grant to access private and protected
members. A friend function can be:
A member of another class
A global function
class B
{
public:
void display(A &a)
{
cout<<"Value of x is : "<<a.x;
}
};
int main()
{
A a; Output
B b; Value of x is : 5
b.display(a);
return 0;
}
In the above example, class B is declared as a friend inside the class A. Therefore, B is a friend of class A. Class B can
access the private members of class A.
Following are some important points about friend functions and classes:
Friends should be used only for limited purpose. Too many functions or external classes are declared as
friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in
object-oriented programming.
Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically.
Friendship is not inherited the concept of friends is not there in Java.
Syntax
class_name::function_name (parameter);
Example
#include <iostream>
class Note
{
static int num; // declare a static data member
public:
static int func () // create static member function
{
return num;
}
};
// initialize the static data member using the class name and the scope resolution operator
int Note :: num = 5;
int main ()
{
// access static member function using the class name and the scope resolution
cout << " The value of the num is: " << Note:: func () << endl;
return 0;
} Output
The value of the num is: 5
this Pointer
In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of
this keyword in C++.
It can be used to pass current object as a parameter to another method.
It can be used to refer current class instance variable.
It can be used to declare indexers.
#include <iostream>
class Employee
{
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
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); //creating an object of Employee
e1.display();
e2.display(); Output
return 0; 101 Sonoo 890000
} 102 Nakul 59000
This part will teach you how to read and write from a file. This requires another standard C++ library called fstream,
which defines three new data types −
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used
to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream
objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument of
the open() member function defines the mode in which the file should be opened.
You can combine two or more of these values by ORing them together. For example if you want to open a file in
write mode and want to truncate it in case that already exists, following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and
close all the opened files. But it is always a good practice that a programmer should close all the opened files
before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream
objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the stream insertion
operator (<<) just as you use that operator to output information to the screen. The only difference is that you
use an ofstream or fstream object instead of the cout object.
#include <fstream>
#include <iostream>
int main () {
char data[100];
// again read the data from the file and display it. Output
infile >> data; Writing to the file
cout << data << endl; Enter your name: Zara
Enter your age: 9
// close the opened file. Reading from the file
infile.close(); Zara
9
return 0;
}
Above examples make use of additional functions from cin object, like getline() function to read the line from
outside and ignore() function to ignore the extra characters left by previous read statement.
The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the
seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a
stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to
the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the
file's starting location. Some examples of positioning the "get" file-position pointer are –