Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

C++ Notes

The document outlines a comprehensive curriculum for a course on Object Oriented Programming using C++, covering fundamental concepts such as language fundamentals, structures, functions, classes, inheritance, pointers, virtual functions, and file handling. It emphasizes the advantages of OOP, including modularity, data hiding, and reusability, while also detailing the basic concepts of objects, classes, inheritance, and polymorphism. Additionally, it provides an overview of C++ as a programming language, its data types, constants, and operators.

Uploaded by

Bharti Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

C++ Notes

The document outlines a comprehensive curriculum for a course on Object Oriented Programming using C++, covering fundamental concepts such as language fundamentals, structures, functions, classes, inheritance, pointers, virtual functions, and file handling. It emphasizes the advantages of OOP, including modularity, data hiding, and reusability, while also detailing the basic concepts of objects, classes, inheritance, and polymorphism. Additionally, it provides an overview of C++ as a programming language, its data types, constants, and operators.

Uploaded by

Bharti Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms.

Shweta Singh Mam

Paper –IV OBJECT ORIENTED PROGRAMMING USING ‘C++’

Max Marks: 100 Min Marks: 40

UNIT - I: Language Fundamental


Advantages of OOP, The Object Oriented Approach, and Characteristics of object oriented languages-
Object Classes, Inheritance, Reusability, and Polymorphism.
Overview of C++: History of C++, Data Types, Constants and Variables, Operators and Expression.
Control structures: if, if-else, nested if-else, while (), do-while (), for (;;), break, continue, switch, goto,
String, Storage class.

UNIT - II: Structure, Function & Array


Structures: A Simple structures, specify the structures, Defining a structure variable, Accessing structures
Member, Enumeration data type.
Function: Function Declaration, Calling Function, Function Defines, Passing Argument to function,
Passing Constant, Passing Value, Reference Argument, Passing struct variable, Overloaded Function,
Inline Function, Default Argument, return statement, returning by reference.
Array: Defining array, array element, initiation array, multi dimensional array, passing array to function.

UNIT - III: Object Classes and Inheritance


Object and Class, Using the class, class construct, class destructors, object as function argument, struct
and classes, array as class member, operator overloading. Type of inheritance, Derive class, Base class.
Access specifier: protected. Overriding, member function.

UNIT - IV: Pointers


Pointers : & and * operator pointer variables, pointer to void ,pointer and array, pointer and function,
pointer and string, memory management, new and delete, pointer to object, pointer to pointer.

UNIT - V: Virtual Function and File & Stream


Virtual Function : Virtual Function, Virtual member function, accesses with pointer, Late binding, pure
virtual function, Friend function, Friend class, static function, this pointer, Templates.
File and Stream: C++ streams, Stream class, string I/O, char I/O, Object I/O, I/O with multiple object,
File pointer, Disk I/O.

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.

ICECDS MSc CS -Sai College Bhilai 1


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

UNIT - I: Language Fundamental


Introduction:
Programmers write instructions in various programming languages to perform their computation tasks such as:
 Machine level Language
 Assembly level Language
 High level Language

Machine level Language:


Machine code or machine language is a set of instructions executed directly by a computer's central processing
unit (CPU). Each instruction performs a very specific task, such as a load, a jump, or an ALU operation on a unit
of data in a CPU register or memory. Every program directly executed by a CPU is made up of a series of such
instructions.

Assembly level Language:


An assembly language (or assembler language) is a low-level programming language for a computer, or other
programmable device, in which there is a very strong (generally one-to-one) correspondence between the
language and the architecture's machine code instructions. Assembly language is converted into executable
machine code by a utility program referred to as an assembler; the conversion process is referred to as
assembly, or assembling the code.

High level Language:


High-level language is any programming language that enables development of a program in much simpler
programming context and is generally independent of the computer's hardware architecture. High-level
language has a higher level of abstraction from the computer, and focuses more on the programming logic
rather than the underlying hardware components such as memory addressing and registers utilization.

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.

The high-level programming languages are broadly categorized in to two categories:

 Procedure oriented programming (POP) language.


 Object oriented programming (OOP) language.

 Procedure Oriented Programming Language

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.

ICECDS MSc CS -Sai College Bhilai 2


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

The disadvantage of the procedure oriented programming languages is:


1. Global data access
2. It does not model real word problem very well
3. No data hiding

Characteristics of procedure oriented programming:


1. Emphasis is on doing things (algorithm)
2. Large programs are divided into smaller programs known as functions.
3. Most of the functions share global data
4. Data move openly around the system from function to function
5. Function transforms data from one form to another.
6. Employs top-down approach in program design.

 Object Oriented Programming

“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”.

Features of the Object Oriented programming


1. Emphasis is on doing rather than procedure.
2. Programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are tied together in the data structure.
5. Data is hidden and can’t be accessed by external functions.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added.
8. Follows bottom-up approach in program design.

ICECDS MSc CS -Sai College Bhilai 3


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

Basic concepts of objects oriented programming

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

ICECDS MSc CS -Sai College Bhilai 4


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

A real-life example of polymorphism, a person at the same


time can have different characteristics. Like a man at the
same time is a father, a husband, an employee. So the
same person posses different behavior in different
situations. This is called polymorphism. Polymorphism is
considered as one of the important features of Object
Oriented Programming.

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.

ICECDS MSc CS -Sai College Bhilai 5


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

ICECDS MSc CS -Sai College Bhilai 6


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

Constant and Variables


A constant is a value that cannot be altered by the program during normal execution, i.e., the value is
constant. When associated with an identifier, a constant is said to be “named,” although the terms “constant”
and “named constant” are often used interchangeably. This is contrasted with a variable, which is an identifier
with a value that can be changed during normal execution, i.e., the value is variable.

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.

Some of the built in operators are

 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Bitwise operators

So, let us have a look all these operators briefly.

ICECDS MSc CS -Sai College Bhilai 7


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

The expressions are of three types


 Arithmetic expression
 Relational expression
 Logical expression

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 (!).

ICECDS MSc CS -Sai College Bhilai 8


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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

 To alter the flow of a program


 Test the logical conditions
 Control the flow of execution as per the selection these conditions can be placed in the program using
decision-making statements.

“C” supports mainly three types of control statements.

1. Decision making statements


 Simple if Statement
 if – else Statement
 Nested if-else statement
 else – if Ladder
 switch statement
2. Loop control statements
 for Loop
 while Loop
 do-while Loop
3. Unconditional control statements
 goto Statement
 break Statement
 continue Statement
 return statement

Decision Making Statements In C Language

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.

(1) Simple “if” statement:

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

ICECDS MSc CS -Sai College Bhilai 9


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

(2) “if-else” Statement:

It is observed that the “if” statement executes only when the


condition following if is true. It does nothing when the
condition is false.
In if-else either True-Block or False – Block will be executed
and not both. The “else” Statement cannot be used without
“if”.

Syntax :
if ( Test Expression or Condition )
{
Statements; /*true block (or) if block */
}
else
{
Statements; /* false block (or) else block */
}

(3) Nested “if–else” Statement:

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.

ICECDS MSc CS -Sai College Bhilai 10


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

(4) The “else – if” Ladder:

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:

if (Test Condition -1)


{
Statement -1;
}
else if ( Test Condition -2)
{
Statement -2;
}
else if ( Test Condition -3)
{
Statement -3;
}
:
:
:
:
else if ( Test Condition –n)
{
Statement –n;
}

else
{
default statement;
}
Rest of the Program Statements-X;

ICECDS MSc CS -Sai College Bhilai 11


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

The above construction is known as else if ladders.


The conditions are evaluated from top to bottom.
As soon as a true condition is found, the statement associated with it is executed and
The control is transferred to the Rest of the Program Statement–X (skipping rest of the ladder).
When all the “n” conditions become false, then the final else containing the default statement will be
executed.

(5) The “switch-case” Statement:

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;

Case Constantvalue-2:Block -2;


(Or)
Statement-2;
break;

ICECDS MSc CS -Sai College Bhilai 12


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _

Case Constant value-n: Block -n;


(Or)
Statement-n;
break;

default: default – block;


}

Loop Control Statements In C Language

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.

(1) For Loop:

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

ICECDS MSc CS -Sai College Bhilai 13


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

(2) The “while” loop :

The while is an entry-controlled loop statement. The test condition is


evaluated and if the condition is true, then the body of the loop is
executed. The execution process is repeated until the test condition
becomes false and the control is transferred out of the loop.

On exit, the program continues with the statement immediately after


the body of the loop. The body of the loop may have one or more
statements. The braces are needed only if the body contains two or
more statements. It’s a good practice to use braces even if the body has
only one statement. The simplest of all the looping structures in C is.
Syntax:
Initialization Expression;
while (Test Condition)
{
Body of the loop
Updation Expression
}

(3) The “do-while “loop :

To execute a part of program or code several times, we can use do-while


loop of C language. The code given between the do and while block will be
executed until condition is true.

The do-while is an exit-controlled loop statement. Because, in do-while, the


condition is checked at the end of the loop. The do-while loop will execute at
least one time even if the condition is false initially. The do-while loop
executes until the condition becomes false.
Syntax:
Initialization Expression;
do
{
Body of the loop
Updation Expression;
} while (Test Condition);

ICECDS MSc CS -Sai College Bhilai 14


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

Unconditional Control Statements In C Language

(1) The “break” Statement :

A break statement terminates the execution of the loop and the


control is transferred to the statement immediately following the
loop. i.e., the break statement is used to terminate loops or to exit
from a switch.
 It can be used within for, while, do-while, or switch statement.
 The break statement is written simply as break;
 In case of inner loops, it terminates the control of inner loop
only.

Syntax:
Jump-statement;
break;
The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

(2) The “continue” Statement:

The continue statement is used to bypass the


remainder of the current pass through a loop. The
loop does not terminate when a continue
statement is encountered. Instead, the remaining
loop statements are skipped and the computation
proceeds directly to the next pass through the
loop.

The continue statement can be included within a


while, do-while, for statement. It is simply written
as “continue”. The continue statement tells the
compiler “Skip the following Statements and
continue with the next Iteration”.

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.

3) The “goto” Statement:

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.

ICECDS MSc CS -Sai College Bhilai 15


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

goto label; label:


............. Statement;
............. .............
............. .............
label: goto label;
statement; Backward Jump
Forward Jump

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;

C++ uses 5 storage classes, namely:


1. Auto, 2. Register, 3. Extern, 4. Static, 5. Mutable

ICECDS MSc CS -Sai College Bhilai 16


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

UNIT - II: Structure, Function & Array

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.

The Syntax Of Structure


struct structure_name
{
// member declarations.
}
In the above declaration, a structure is declared by preceding the struct keyword followed by the identifier
(structure name). Inside the curly braces, we can declare the member variables of different types. Consider the
following situation:
struct Student
{
char name[20];
int id;
int age;
}
In the above case, Student is a structure contains three variables name, id, and age. When the structure is
declared, no memory is allocated. When the variable of a structure is created, then the memory is allocated.

How to create the instance of Structure?

Structure variable can be defined as:

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.

How to access the variable of Structure:

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.

ICECDS MSc CS -Sai College Bhilai 17


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

Points to remember for C++ Enum


 enum improves type safety
 enum can be easily used in switch
 enum can be traversed
 enum can have fields, constructors and methods
 enum may implement many interfaces but cannot extend any class because it internally extends
Enum class

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.

Advantage of functions in C++

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

return_type function_name (data_type parameter...)


{
//code to be executed
}

ICECDS MSc CS -Sai College Bhilai 18


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

A function declaration has the following parts −

return_type function_name( parameter list );

For the above defined function max(), following is the function declaration −

int max(int num1, int num2);

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.

ICECDS MSc CS -Sai College Bhilai 19


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

 Call by value in C++


In call by value, original value is not modified.

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

 Call by reference in C++


In call by reference, original value is modified because we pass reference (address).

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.

 Difference between call by value and call by reference in C++

No. Call by value Call by reference

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.

ICECDS MSc CS -Sai College Bhilai 20


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 Syntax for an inline function:

inline return_type function_name(parameters)


{
// function code?
}

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

 We cannot provide the in lining to the functions in the following circumstances:


 If a function is recursive.
 If a function contains a loop like for, while, do-while loop.
 If a function contains static variables.
 If a function contains a switch or go to statement
 When do we require an inline function?

 An inline function can be used in the following scenarios:


 An inline function can be used when the performance is required.
 It can be used over the macros.
 We can use the inline function outside the class so that we can hide the internal implementation of
the function.

 Advantages of inline function


 In the inline function, we do not need to call a function, so it does not cause any overhead.
 It also saves the overhead of the return statement from a function.
 It does not require any stack on which we can push or pop the variables as it does not perform any
function calling.
 An inline function is mainly beneficial for the embedded systems as it yields less code than a normal
function.

Default arguments in C++


In a function, arguments are defined as the values passed when a function is called. Values passed are the
source, and the receiving function is the destination.

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

 Characteristics for defining the default arguments

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

ICECDS MSc CS -Sai College Bhilai 21


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 All the values that will be given default value will be on the right.

 Example

Void function (int x, int y, int z = 0)


Explanation - The above function is valid. Here z is the value that is predefined as a part of the default argument.

Void function (int x, int z = 0, int y)


Explanation - The above function is invalid. Here z is the value defined in between, and it is not accepted.

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.

Functions in C++ can return a reference as it’s returns a pointer.


When function returns a reference it means it returns a implicit pointer.
Return by reference is very different from Call by reference. Functions behaves a very important role when
variable or pointers are returned as reference.
Syntax

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 –

type arrayName [ arraySize ];

ICECDS MSc CS -Sai College Bhilai 22


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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 –

 Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array. For example −

double salary = balance[9];


The above statement will take 10th element from the array and assign the value to salary variable.

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

 Passing arrays to functions


You can pass to the function a pointer to an array by specifying the array's name without an index.

 Return array from functions


C++ allows a function to return an array.

ICECDS MSc CS -Sai College Bhilai 23


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

 Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array
with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3}, /* initializers for row indexed by 0 */
{4, 5, 6, 7}, /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to
previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

 Accessing Two-Dimensional Array Elements


An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the
array. For example −
int val = a[2][3];
The above statement will take 4th element from the 3rd row of the array. You can verify it in the above
diagram.

ICECDS MSc CS -Sai College Bhilai 24


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

Passing Arrays to Functions


C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an
array by specifying the array's name without an index.

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.

 Way-1 Formal parameters as a pointer as follows −

void myFunction(int *param)


{
.
.
.
}
 Way-2 Formal parameters as a sized array as follows −

void myFunction(int param[10])


{
.
.
.
}
 Way-3 Formal parameters as an unsized array as follows −

void myFunction(int param[])


{
.
.
.
}

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

ICECDS MSc CS -Sai College Bhilai 25


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

UNIT - III: Object Classes and Inheritance

 C++ Object and Class


Since C++ is an object-oriented language, program is designed using objects and classes in C++.

 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
}

 Example - C++ Object and Class


Let's see an example of class that has two fields: id and name. It creates instance of the class, initializes the object
and prints the object value.

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

ICECDS MSc CS -Sai College Bhilai 26


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 Example - C++ Class: Initialize and Display data through method


Let's see another example of C++ class where we are initializing and displaying object through method.

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

 Example - C++ Class: Store and Display Employee Information


Let's see another example of C++ class where we are storing and displaying employee information using method.

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)

ICECDS MSc CS -Sai College Bhilai 27


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

{
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

 C++ Default Constructor


A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
Example - C++ default Constructor.

class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};

int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}

 C++ Parameterized Constructor


A constructor which has parameters is called parameterized constructor. It is used to provide different values to
distinct objects.
Example - C++ Parameterized Constructor.

class Employee
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;

Employee(int i, string n, float s)

ICECDS MSc CS -Sai College Bhilai 28


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

{
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;
}

ICECDS MSc CS -Sai College Bhilai 29


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 Object as Function Arguments


Objects are passed to a function as argument like variable of any primitive data type. There are 2 ways of passing
object as argument to a function:
 Pass object by value to a function
In this, a copy of object is sent to the function, hence any changes made to the object inside the function do
not affect the object used to call the function.
 Pass object by reference to the function
In this, address of the object is passed to the function, hence the any changes made to the object inside the
called function is reflected to the actual object.

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

ICECDS MSc CS -Sai College Bhilai 30


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 Structure and Class

Features Structure Class


A structure is a grouping of variables of In C++, a class is defined as a collection of
Definition various data types referenced by the same related variables and functions contained
name. within a single structure.

If no access specifier is specified, all If no access specifier is defined, all


Basic
members are set to 'public'. members are set to 'private'.

struct structure_name class class_name


{ {
type struct_member 1; data member;
type struct_member 2; member function;
Declaration type struct_member 3; };
.
type struct_memberN;
};

Structure instance is called the 'structure


Instance A class instance is called 'object'.
variable'.

Inheritance It does not support inheritance. It supports inheritance.


Memory
Memory is allocated on the stack. Memory is allocated on the heap.
Allocated
Nature Value Type Reference Type

Purpose Grouping of data Data abstraction and further inheritance.

Usage It is used for smaller amounts of data. It is used for a huge amount of data.

Null values Not possible It may have null values.

Requires
It may have only parameterized It may have all the types of constructors
constructor and
constructor. and destructors.
destructor

 Arrays as Class Members


Arrays can be declared as the members of a class. The arrays can be declared as private, public or protected
members of the class.
Example - Arrays as Class Members

#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

void student :: getdata ()


{
cout<<"\nEnter roll no: ";
cin>>roll_no;
for(int i=0; i<size; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}

void student :: tot_marks() //calculating total marks


{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}

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

ICECDS MSc CS -Sai College Bhilai 32


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 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;
}

 The Process of Overloading involves the following steps


 Create a class that define the dataType that is to be used in the overloading operations.
 Declare the operator function operator OP () in the public part of class it may be either a member function
or a friend function.
 Define the operator function to implement the require function.

 Unary Operators Overloading


The unary operators operate on a single operand and following are the examples of Unary operators −
 The increment (++) and decrement (--) operators.
 The unary minus (-) operator.
 The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears
on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well
like obj++ or obj--.
Example - Unary Operators Overloading

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

void space :: getdata(int a, int b, int c)


{
x=a;
y=b;
z=c;
}

void space :: display(void)

ICECDS MSc CS -Sai College Bhilai 33


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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

 Binary Operators Overloading


The binary operators take two arguments and following are the examples of Binary operators. You use binary
operators very frequently like addition (+) operator, subtraction (-) operator and division (/) operator.
Example - Binary Operators Overloading

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

ICECDS MSc CS -Sai College Bhilai 34


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

{
cout<<x<<"+j"<<y<<"\n";
}
void main()
{
clrscr();
complex c1,c2,c3;

c1=complex (2.3, 3.5); // invoke Constructor 1


c2=complex (1.6, 2.7); // invoke Constructor 2
c3=c1+c2;

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";
}
};

class Derived:public Base


{
public :
void show()
{
cout<<"Derivrd Class";
}
}; // In this example function show () is overriding in the Derived class

ICECDS MSc CS -Sai College Bhilai 35


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 Function call binding with class object


Connecting the function call to function body is called binding. When it is done before the program is run it’s
called Early Binding or Static Binding or Compile Time Binding
Example - Function call binding with class object
class Base
{
public:
void show() // Method Overriding
{
cout<<"Base Class";
}
};

class Derived:public Base


{
public :
void show()
{
cout<<"Derivrd 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.

 Function call binding using base class pointer


But when we use a Base class pointer or reference to hold derived class object then function call binding gives
some unexpected result. [ () = this pointer ]
Example - Function call binding using base class pointer

class Base
{
public:
void show() // Method Overriding
{
cout<<"Base Class";
}
};

class Derived:public Base


{
public :
void show()

ICECDS MSc CS -Sai College Bhilai 36


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

{
cout<<"Derivrd Class";
}
};

void main()
{
Base *b; // Base Class Object
Derived d; // Derived Class Object
b=&d;
dshow(); // 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.

 Why and when to use inheritance?


Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods fuel Amount (),
capacity (), apply Brakes () will be same for all of the three classes. If we create these classes avoiding
inheritance then we have to write all of these functions in each of the three classes.

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

ICECDS MSc CS -Sai College Bhilai 37


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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

Child obj1; // an object of class child has all data members


and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;

cout << "Child id is " << obj1.id_c << endl;


cout << "Parent id is " << obj1.id_p << endl;

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

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};

ICECDS MSc CS -Sai College Bhilai 39


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 Types of Inheritance in 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;
}
};

class Car: public Vehicle


{
};

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

ICECDS MSc CS -Sai College Bhilai 40


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

Example
class Vehicle // first base class
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

class FourWheeler // second base class


{
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle" << endl;
}
};

class Car: public Vehicle, public FourWheeler


{
};

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

class fourWheeler: public Vehicle


{
public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};

ICECDS MSc CS -Sai College Bhilai 41


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

class Car: public fourWheeler


{
public:
Car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
OUTPUT
int main()
This is a Vehicle
{
Car obj; Objects with 4 wheels are vehicles
getch();
Car has 4 Wheels
return 0;
}

 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;
}
};

class Car: public Vehicle


{
};

class Bus: public Vehicle


{
};

int main()
{ OUTPUT
Car obj1;
Bus obj2; This is a Vehicle
getch(); This is a Vehicle
return 0;
}

ICECDS MSc CS -Sai College Bhilai 42


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 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";
}
};

class Car: public Vehicle


{
};
class Bus: public Vehicle, public Fare
{
};
int main()
{
Bus obj2;
getch();
return 0;
}

OUTPUT

This is a Vehicle
Fare of Vehicle

 A special case of hybrid inheritance : Multipath inheritance:


A derived class with two base classes and these two base classes have one common base class is called
multipath inheritance. An ambiguity can arise in this type of inheritance.

ICECDS MSc CS -Sai College Bhilai 43


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

Example
class ClassA
{
public:
int a;
};

class ClassB : public ClassA


{
public:
int b;
};
class ClassC : public ClassA
{
public:
int c;
};

class ClassD : public ClassB, public ClassC


{
public:
int d;
};
OUTPUT
void main() A from ClassB: 10
{ A from ClassC: 100
ClassD obj; B: 20
obj.ClassB::a = 10; C: 30
obj.ClassC::a = 100; D: 40

obj.b = 20;
obj.c = 30;
obj.d = 40;

cout << "\n A from ClassB : " << obj.ClassB::a;


cout << "\n A from ClassC : " << obj.ClassC::a;

cout << "\n B : " << obj.b;


cout << "\n C : " << obj.c;
cout << "\n D : " << obj.d;
}

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.

ICECDS MSc CS -Sai College Bhilai 44


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

UNIT - IV: Pointers

 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

 How Pointer Works in C++ var [** = Chain Pointer]


int var = 10; [10] 20 30
#2008
int *ptr = &var;
*ptr = 20;

int **ptr = &ptr’


**ptr = 20;

 How to use a pointer?


 Define a pointer variable
 Assigning the address of a variable to a pointer using unary operator (&) which returns the address of that
variable.
 Accessing the value stored in the address using unary operator (*) which returns the value of the variable
located at the address specified by its operand.
The reason we associate data type to a pointer is that it knows how many bytes the data is stored in. When we
increment a pointer, we increase the pointer by the size of data type to which it points.
Example
void geeks()
{
int var = 20;
int *ptr;
ptr = &var;

printf("Value at ptr = %p \n",ptr);


printf("Value at var = %d \n",var);
printf("Value at *ptr = %d \n", *ptr);
}
OUTPUT
int main()
{ Value at ptr = 0x7ffcb9e9ea4c
geeks(); Value at var = 20
} Value at *ptr = 20

 References and Pointers


There are 3 ways to pass C++ arguments to a function:
1. call-by-value
2. call-by-reference with pointer argument
3. call-by-reference with reference argument

ICECDS MSc CS -Sai College Bhilai 45


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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

// variable is of double type


double d = 9.0;

// 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; // assign float address to void

cout << &f << endl; OUTPUT


cout << ptr << endl;
0xffd117ac
0xffd117ac
return 0;
}
Here, the pointer ptr is given the value of &f. The output shows that the void pointer ptr stores the address of a
float variable f

 Printing the Content of Void Pointer


To print the content of a void pointer, we use the static_cast operator. It converts the pointer from void* type to
the respective data type of the address the pointer is storing:
Example
#include <iostream>
int main()
{
void* ptr;
float f = 2.3f;

ptr = &f;

ICECDS MSc CS -Sai College Bhilai 46


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

cout << "The content of pointer is ";


cout << *(static_cast<float*>(ptr)); // use type casting to print pointer content
return 0;
OUTPUT
}
The content of pointer is 2.30xffd117ac

 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*

 Pointers and Arrays


Pointers are variables that hold addresses of other variables. Not only can a pointer store the address of a single
variable, it can also store the address of cells of an array.
Example:
int *ptr;
int arr[5];
ptr = arr; // store the address of the first element of arr in ptr

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

 Pointers and String


Example
int main()
{
char name[ ]= "Sam";
char *p;
p = name; // for string, only this declaration will store its base address
while( *p != '\0')
{
cout << *p;
p++; OUTPUT
} SAM
return 0;
}

ICECDS MSc CS -Sai College Bhilai 47


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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

 Passing Strings to Functions


This is the same as we do with other arrays. The only difference is that this is an array of characters
Example
int main(){
char arr[30];
cout << "Enter a word" << endl;
cin >> arr;
display(arr);
return 0;
} OUTPUT
oid display( char ch[] ) Enter a word
{ SAI COLLAGE
cout << ch; SAI COLLAGE
}

Example - Length of String


int main()
{
char name[ ]= "Hello";
int len1, len2; OUTPUT
Length of Hello = 5
len1 = strlen(name); Length of Hello World = 11
len2 = strlen("Hello World");

cout << "Length of " << name << " = " << len1 << endl;
cout << "Length of " << "Hello World" << " = " << len2 << endl;
return 0;
}

 Memory Management: New and Delete


C++ allows us to allocate the memory of a variable or an array in run time. This is known as dynamic memory
allocation. In other programming languages such as Java and Python, the compiler automatically manages the
memories allocated to variables. But this is not the case in C++.
In C++, we need to deallocate the dynamically allocated memory manually after we have no use for the variable.
We can allocate and then deallocate memory dynamically using the new and delete operators respectively.

 New Operator
The new operator allocates memory to a variable. For example,

int* pointVar; // declare an int pointer


pointVar = new int; // dynamically allocate memory using the new keyword
*pointVar = 45; // assign value to allocated memory

Here, we have dynamically allocated memory for an int variable using the new operator.

ICECDS MSc CS -Sai College Bhilai 48


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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;

int* pointVar; // declare an int pointer


pointVar = new int; // dynamically allocate memory for an int variable
*pointVar = 45; // assign value to the variable memory
cout << *pointVar; // print the value stored in memory
delete pointVar; // deallocate the memory

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 = new int;


point 2 = new float;

* point 1 = 100;
* point 2 = 98.32;

cout<< * point 1;
cout<< * point 2;

delete point 1;
delete point 2;

getch();
return 0;
}

ICECDS MSc CS -Sai College Bhilai 49


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 New and Delete Operator for Objects


Example
#include <iostream> OUTPUT
class Student Age = 12
{
int age;
public:

Student (): age (12) // constructor initializes age to 12


{
}

void getAge()
{
cout << "Age = " << age << endl;
}
};

int main()
{
Student* ptr = new Student (); // dynamically declare Student object
PtrgetAge (); // 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:
PtrgetAge ();
Notice the arrow operator. This operator is used to access class members using pointers.

 Pointer to Pointer (Double Pointer)


We already know that a pointer points to a location in memory and thus used to store the address of variables. So,
when we define a pointer to pointer. The first pointer is used to store the address of the variable. And the second
pointer is used to store the address of the first pointer. That is why they are also known as double pointers.

 How to declare a pointer to pointer in C?


Syntax
int **ptr; // declaring double pointers

Pointer to pointer var pointer to var actual variable with a value

ptr2 ptr1 var


[4020] [2008] [10]
#3096 #4020 #2008

Address of pointer p2 Address of pointer p1 Address of var

ICECDS MSc CS -Sai College Bhilai 50


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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;

int *ptr2; // pointer for var


int **ptr1; // double pointer for ptr2

ptr2 = &var; // storing address of var in ptr2


ptr1 = &ptr2; // Storing address of ptr2 in ptr1

printf("Value of var = %d\n", var );


printf("Value of var using single pointer = %d\n", *ptr2 );
printf("Value of var using double pointer = %d\n", **ptr1);

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;

op = & ob; // get address of ob


op --> read(10);
cout<<op --> getint();

getch();
}

ICECDS MSc CS -Sai College Bhilai 51


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

UNIT - V: Virtual Function and File & Stream

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

 Rules of Virtual Function


 Virtual functions must be members of some class.
 Virtual functions cannot be static members.
 They are accessed through object pointers.
 They can be a friend of another class.
 A virtual function must be defined in the base class, even though it is not used.
 The prototypes of a virtual function of the base class and all the derived classes must be identical. If the
two functions with the same name but different prototypes, C++ will consider them as the overloaded
functions.
 We cannot have a virtual constructor, but we can have a virtual destructor
 Consider the situation when we don't use the virtual keyword.
Example
#include <iostream>
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
} OUTPUT
Derived Class is invoked

ICECDS MSc CS -Sai College Bhilai 52


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 Pure Virtual Function


 A virtual function is not used for performing any task. It only serves as a placeholder.
 When the function has no definition, such function is known as "do-nothing" function.
 The "do-nothing" function is known as a pure virtual function. A pure virtual function is a function declared
in the base class that has no definition relative to the base class.
 A class containing the pure virtual function cannot be used to declare the objects of its own, such classes
are known as abstract base classes.
 The main objective of the base class is to provide the traits to the derived classes and to create the base
pointer used for achieving the runtime polymorphism.

Pure virtual function can be defined as:


virtual void display() = 0;

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.

ICECDS MSc CS -Sai College Bhilai 53


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 Early binding and Late binding


Binding refers to the process of converting identifiers (such as variable and performance names) into addresses.
Binding is done for each variable and functions. For functions, it means that matching the call with the right function
definition by the compiler. It takes place either at compile time or at runtime.

 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

ICECDS MSc CS -Sai College Bhilai 54


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 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";
}
};

class Derived: public Base


{
public:
void show()
{
cout<<"In Derived \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.

 Declaration of friend function

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.

ICECDS MSc CS -Sai College Bhilai 55


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

 Characteristics of a Friend function:

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

Example of Friend Function


#include <iostream.h>
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};

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

ICECDS MSc CS -Sai College Bhilai 56


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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

Example of a friend class.


#include <iostream>
class A
{
int x =5;
friend class B; // friend class.
};

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.

 Static Member Functions


The static member functions are special functions used to access the static data members or other static member
functions. A member function is defined using the static keyword. A static member function shares the single copy
of the member function to any number of the class' objects. We can access the static member function using the
class name or class' objects. If the static member function accesses any non-static data member or non-static
member function, it throws an error.

Syntax
class_name::function_name (parameter);

ICECDS MSc CS -Sai College Bhilai 57


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

Here, the class_name is the name of the class.


function_name: The function name is the name of the static member function.
parameter: It defines the name of the pass arguments to the static member function.

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.

this Pointer Example

#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;
}

ICECDS MSc CS -Sai College Bhilai 58


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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

 Files and Streams


So far, we have been using the iostream standard library, which provides cin and cout methods for reading from
standard input and writing to standard output respectively.

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 −

Sr.No Data Type Description


This data type represents the output file stream and is used to create files and to
1 ofstream
write information to files.
This data type represents the input file stream and is used to read information from
2 ifstream
files.
This data type represents the file stream generally, and has the capabilities of both
3 fstream ofstream and ifstream which means it can create files, write information to files,
and read information from files.

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.

Sr.No Mode Flag Description


1 ios::app Append mode. All output to that file to be appended to the end.
2 ios::ate Open a file for output and move the read/write control to the end of the file.
3 ios::in Open a file for reading.
4 ios::out Open a file for writing.
5 ios::trunc If the file already exists, its contents will be truncated before opening the file.

ICECDS MSc CS -Sai College Bhilai 59


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

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.

 Reading from a File


You read information from a file into your program using the stream extraction operator (>>) just as you use
that operator to input information from the keyboard. The only difference is that you use an ifstream or
fstream object instead of the cin object.

Read and Write Example


Following is the C++ program which opens a file in reading and writing mode. After writing information entered
by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen

#include <fstream>
#include <iostream>

int main () {
char data[100];

// open a file in write mode.


ofstream outfile;
outfile.open("afile.dat");

cout << "Writing to the file" << endl;


cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.


outfile << data << endl;

cout << "Enter your age: ";


cin >> data;
cin.ignore();

ICECDS MSc CS -Sai College Bhilai 60


OBJECT ORIENTED PROGRAMMING USING ‘C++’ BY Ms. Shweta Singh Mam

// again write inputted data into the file.


outfile << data << endl;

// close the opened file.


outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("afile.dat");

cout << "Reading from the file" << endl;


infile >> data;

// write the data at the screen.


cout << data << endl;

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

 File Position Pointers


Both istream and ostream provide member functions for repositioning the file-position pointer. These member
functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.

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 –

// position to the nth byte of fileObject (assumes ios::beg)


fileObject.seekg( n );

// position n bytes forward in fileObject


fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObject


fileObject.seekg( n, ios::end );

// position at end of fileObject


fileObject.seekg( 0, ios::end );
ICECDS MSc CS -Sai College Bhilai 61

You might also like