You are on page 1of 143

C++ - 1

OBJECT-ORIENTED
PROGRAMMING

By:- Prof. Prajakta Deepak Shetye


A simple program in C++
#include<iostream.h> /header file
#include<conio.h>
void main()
{
int num1,num2,num3; // variables
cout<<“Enter the numbers”;
cin>>num1>>num2;
num3=num1+num2;
cout<<”The sum of num1 & num2 is /t”<<num3;
} 2

By:- Prof. Prajakta Deepak Shetye


Data Types
DATA TYPES

USER-DEFINED BUILT-IN DERIVED

• STRUCTURE • ARRAY
INTEGRAL VOID FLOATING
• CLASS • FUNCTION
• UNION • POINTER
• ENUMERATION

3
INT CHAR FLOAT DOUBLE

By:- Prof. Prajakta Deepak Shetye


VARIABLES
• A name that refers to value. In C++, all the variables must be declared before they are used in executed
statements. They can be declared anywhere in the program.
• Declaration of variables:- C++ allows the declaration of a variable anywhere in the scope. This means
that a variable can be declared right at the place of its first use. This makes the program much easier to
write and reduces the errors that may be caused by having to scan back and forth.
• A variable is created as follows:
datatype variable-name;

• Reference Variables:- C++ introduces a new kind of variable known as the reference variable. A
reference variable provides an alias for a previously defined variable.
• A reference variable is created as follows:
datatype & reference-name = variable-name;

By:- Prof. Prajakta Deepak Shetye


Variable Scope in C++
• A scope is a region of the program and broadly speaking there are three places, where variables can be
declared −
• Inside a function or a block which is called local variables,
• In the definition of function parameters which is called formal parameters.
• Outside of all functions which is called global variables.

By:- Prof. Prajakta Deepak Shetye


Local Variables

Variables that are declared inside a function or block are local variables. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions
outside their own. Following is the example using local variables −
#include <iostream>

int main ()
{
int a, b; int c; // Local variable declaration:
a = 10; b = 20; // actual initialization
c = a + b;
cout << c;
return 0;
}
6

By:- Prof. Prajakta Deepak Shetye


Global Variables

Global variables are defined outside of all the functions, usually on top of the program. The global
variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. Following is the example using global and local
variables −
#include <iostream>

int g; // Global variable declaration:

int main ()
{
int a, b; // Local variable declaration:
a = 10; b = 20; // actual initialization
g = a + b;
cout << g;
return 0;
7
}

By:- Prof. Prajakta Deepak Shetye


OPERATORS
• BINARY OPERATOR

• RELATIONAL OPERATOR

• INCREMENT/DECREMENT OPERATOR

• LOGICAL OPERATOR

• BITWISE OPERATOR

By:- Prof. Prajakta Deepak Shetye


BINARY OPERATOR

Operator Symbol Form Operation


ADDITION + X +Y x plus y

SUBTRACTION - X -Y x minus y

MULTIPLICATION * X *Y x multiplied by y

DIVISION / X /Y x divided y

MODULUS % X %Y x divided y
(remainder)

By:- Prof. Prajakta Deepak Shetye


RELATIONAL OPERATOR
Operator Symbol Form Operation
GREATER THAN > X >Y true if x is greater than y, false
otherwise
LESS THAN < X <Y true if x is less than y, false
otherwise
GREATER THAN OR >= X >= Y true if x is greater than or equal to y,
EQUAL TO false otherwise
LESS THAN OR EQUAL <= X <= Y true if x is less than or equal to y,
TO false otherwise
EQUAL TO == X == Y true if x equals y, false otherwise

NOT EQUAL TO != X != Y true if x does not equal y, false


otherwise
10

By:- Prof. Prajakta Deepak Shetye


INCREMENT/DECREMENT
OPERATOR
Operator Symbol Form Operation
Prefix increment ++ ++X Increment x, then
evaluate x
Prefix decrement -- - -X Decrement x, then
evaluate x
Postfix increment ++ X++ Evaluate x, then
increment x
Postfix decrement -- X- - Evaluate x, then
decrement x

11

By:- Prof. Prajakta Deepak Shetye


PREFIX INCREMENT

ASSUME X=5
X IS INCREMENTED BEFORE EVALUTION

EXPRESSION X=1+X

A=++X

A=6
12

By:- Prof. Prajakta Deepak Shetye


POSTFIX INCREMENT

ASSUME X=5
X IS INCREMENTEDAFTER EVALUTION

EXPRESSION X=X+1

A=X++

A=5
13

By:- Prof. Prajakta Deepak Shetye


LOGICAL OPERATOR

Operator Symbol Form Operation


LOGICAL NOT ! !X true if x is false, or
false if x is true
LOGICAL AND && X && Y true if both x and y are
true, false otherwise
LOGICAL OR || X || Y true if either x or y are
true, false otherwise

14

By:- Prof. Prajakta Deepak Shetye


BITWISE OPERATOR
Operator Symbol Form Operation
BINARY AND & A&B Operator copies a bit to the result if it exists in
both operands.
BINARY OR | A|B Operator copies a bit if it exists in either operand.

BINARY XOR ^ A^B Operator copies the bit if it is set in one operand
but not both.
BINARY ONE ~ ~A Operator is unary and has the effect of 'flipping'
COMPLEMENT bits.
BINARY RIGHT SHIFTER >> A>> The left operands value is moved right by the
number of bits specified by the right operand.
BINARY LEFT SHIFTER << A<< The left operands value is moved left by the
number of bits specified by the right operand.
15

By:- Prof. Prajakta Deepak Shetye


TRUTH TABLE FOR BINARY AND, OR and XOR

P Q P&Q P|Q P^Q


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

16

By:- Prof. Prajakta Deepak Shetye


Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101

A & B EXP A | B EXP A ^ B EXP ~A A>>2 A<<2

A = 0011 1100 A = 0011 1100 A = 0011 1100 A = 0011 1100 A = 0011 1100 A = 0011 1100
B = 0000 1101 B = 0000 1101 B = 0000 1101
------------------- ------------------- ------------------- ------------------- ------------------- -------------------
=0000 1100 =0011 1101 =0011 0001 =1100 0011 =0000 1111 =1111 0000

17

By:- Prof. Prajakta Deepak Shetye


FLOW CONTROL
DECISION MAKING
Decision making structures require that the programmer specify one or more conditions to be evaluated
or tested by the program, along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to
be false.

18

By:- Prof. Prajakta Deepak Shetye


IF STRUCTURE

A conditional branch is a statement that causes the program to change the path of execution based on the
value of an expression. The most basic conditional branch is if statement.
if (Condition)
statements1;
else
statements2;

Example:-
void main()
{
int no;
cout << "Enter a number: ";
cin >> no;
if (no > 10)
cout << no << "is greater than 10" << endl;
else
cout << no << "is not greater than 10" << endl;
}
19

By:- Prof. Prajakta Deepak Shetye


IF……ELSE STRUCTURE

void main()
{
int no;
cout << "Enter a number: ";
cin >> no;
if (no > 10)
cout << no << "is greater than 10" << endl;
else if (no < 5)
cout << no << "is less than 5" << endl;
else
cout << no << "is between 5 and 10" << endl;
}

20

By:- Prof. Prajakta Deepak Shetye


IF……ELSE NESTING STRUCTURE

void main()
{
int no;
cout << "Enter a number: ";
cin >> no;
if (no > 10)
{
if (no < 20)
cout << no << "is between 10 and 20" << endl;
else cout << no << "is greater than 20" << endl;
}
}

21

By:- Prof. Prajakta Deepak Shetye


SWITCH STATEMENT STRUCTURE

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a
case, and the variable being switched on is checked for each case Syntax:-
..

switch(expression)
{
case constant-expression :
statement(s);
break; //Optional
case constant-expression :
statement(s);
break; //optional

// you can have any number of case statements.

default ://Optional
statement(s);
22
}

By:- Prof. Prajakta Deepak Shetye


#include <iostream>
int main ()
{
char grade = 'D’;
switch(grade)
{
case 'A’ :
cout << "Excellent!" << endl;
break;
case 'B’ :
cout << “Good!" << endl;
break;
case 'C’ :
cout << "Well done" << endl;
break;
case 'D’ :
cout << "You passed" << endl;
break;
case 'F’ :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0; 23
}

By:- Prof. Prajakta Deepak Shetye


FLOW CONTROL
LOOP STATEMENTS
There may be a situation, when you need to execute a block of code several number of times. In general,
statements are executed sequentially: The first statement in a function is executed first, followed by the
second, and so on. Programming languages provide various control structures that allow for more
complicated execution paths. A loop statement allows us to execute a statement or group of statements
multiple times and following is the general from of a loop statement in most of the programming languages −

24

By:- Prof. Prajakta Deepak Shetye


WHILE LOOP

A while loop statement repeatedly executes a target statement as long as a given condition is true.
Syntax:-

while (expression)
{
STATEMENTS;
}
STATEMENTS;

25

By:- Prof. Prajakta Deepak Shetye


#include <iostream>
OUTPUT:
int main () value of a: 10
{ value of a: 11
// Local variable declaration: value of a: 12
int a = 10; value of a: 13
value of a: 14
// while loop execution value of a: 15
while( a < 20 ) { value of a: 16
cout << "value of a: " << a << endl; value of a: 17
a++; value of a: 18
} value of a: 19

return 0;
}

26

By:- Prof. Prajakta Deepak Shetye


DO……WHILE LOOP

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least
one time Syntax:-
.

d0{
statements;
}
while(condition);

27

By:- Prof. Prajakta Deepak Shetye


#include <iostream>

int main () {
// Local variable declaration: value of a: 10
int a = 10; value of a: 11
value of a: 12
// do loop execution value of a: 13
do { value of a: 14
cout << "value of a: " << a << endl; value of a: 15
a = a + 1; value of a: 16
} while( a < 20 ); value of a: 17
value of a: 18
return 0; value of a: 19
}

28

By:- Prof. Prajakta Deepak Shetye


FOR LOOP

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute
a specific number of times Syntax:-
.

for(init; condition; increment/decrement)


{
statements;
}

29

By:- Prof. Prajakta Deepak Shetye


• The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables.You are not required to put a statement here, as long as a semicolon appears.

• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the
loop does not execute and flow of control jumps to the next statement just after the for loop.

• After the body of the for loop executes, the flow of control jumps back up to the increment statement.
This statement can be left blank, as long as a semicolon appears after the condition.

• The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body
of loop, then increment step, and then again condition). After the condition becomes false, the for loop
terminates

30

By:- Prof. Prajakta Deepak Shetye


#include <iostream>

int main () value of a: 10


{ value of a: 11
// for loop execution value of a: 12
for( int a = 10; a < 20; a = a + 1 ) value of a: 13
{ value of a: 14
cout << "value of a: " << a << endl; value of a: 15
} value of a: 16
value of a: 17
return 0; value of a: 18
} value of a: 19

31

By:- Prof. Prajakta Deepak Shetye


FUNCTIONS
• A function is a group of statements that together perform a task. Every C++ program has at least one
function, which is main().
• You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division usually is such that each function performs a specific
task.
• A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
• A function is known with various names like a method or a sub-routine or a procedure etc.

32

By:- Prof. Prajakta Deepak Shetye


The general form of a C++ function definition is as follows −
return_type function_name( parameter list )
{
body of the function
}
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.
33

By:- Prof. Prajakta Deepak Shetye


EXAMPLE

// function returning the max between two numbers

int max(int num1, int num2) {


// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

34

By:- Prof. Prajakta Deepak Shetye


FUNCTION DECLARATION
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);

35

By:- Prof. Prajakta Deepak Shetye


CALLING FUNCTION
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.

36

By:- Prof. Prajakta Deepak Shetye


#include <iostream.h>
// function returning the max between two numbers
int max(int num1, int num2) {
// function declaration // local variable declaration
int max(int num1, int num2); int result;

int main () { if (num1 > num2)


// local variable declaration: result = num1;
int a = 100; else
int b = 200; result = num2;
int ret;
return result;
// calling a function to get max value. }
ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
} 37

By:- Prof. Prajakta Deepak Shetye


FUNCTION ARGUMENTS
If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry into
the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function −
1. Call by value
2. Call by reference

38

By:- Prof. Prajakta Deepak Shetye


CALL BY VALUE
The call by value method of passing arguments to a function copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to the parameter inside the function have no
effect on the argument.
By default, C++ uses call by value to pass arguments. In general, this means that code within a function
cannot alter the arguments used to call the function.

39

By:- Prof. Prajakta Deepak Shetye


#include <iostream.h>

// function declaration
// function definition to swap the void swap(int x, int y);
values.
void swap(int x, int y) { int main () {
int temp; // local variable declaration:
int a = 100;
temp = x; /* save the value of x */ int b = 200;
x = y; /* put y into x */
y = temp; /* put x into y */ cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
return;
} // calling a function to swap the values.
swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl; 40

By:- Prof. Prajakta Deepak Shetye


return 0;
}
OUTPUT:-

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

41

By:- Prof. Prajakta Deepak Shetye


CALL BY REFERENCE
The call by reference method of passing arguments to a function copies the reference of an argument into
the formal parameter. Inside the function, the reference is used to access the actual argument used in the
call. This means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument reference is passed to the functions just like any other value.

42

By:- Prof. Prajakta Deepak Shetye


#include <iostream.h>

// function declaration
void swap(int &x, int &y);
// function definition to swap the
int main () {
values. // local variable declaration:
void swap(int &x, int &y) { int a = 100;
int temp; int b = 200;
temp = x; /* save the value at
address x */ cout << "Before swap, value of a :" << a << endl;
x = y; /* put y into x */ cout << "Before swap, value of b :" << b << endl;
y = temp; /* put x into y */
/* calling a function to swap the values using variable
return; reference.*/
} swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;
43

return 0;
By:- Prof. Prajakta Deepak Shetye }
OUTPUT:-

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

44

By:- Prof. Prajakta Deepak Shetye


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

45

By:- Prof. Prajakta Deepak Shetye


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 ];
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
You can initialize C++ array elements either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

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

46

By:- Prof. Prajakta Deepak Shetye


POINTERS
Every variable is a memory location and every memory location has its address defined which can be
accessed using ampersand (&) operator which denotes an address in memory.
#include <iostream>
int main () {
int var1;
char var2[10];
cout << "Address of var1 variable: "; Address of var1 variable: 0xbfebd5c0
cout << &var1 << endl; Address of var2 variable: 0xbfebd5b6
cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0;
47
}
By:- Prof. Prajakta Deepak Shetye
POINTERS
What are Pointers?
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you
must declare a pointer before you can work with it. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer
variable. The asterisk you used to declare a pointer.
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
48

By:- Prof. Prajakta Deepak Shetye


#include <iostream>
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable


Value of var variable: 20
cout << "Value of var variable: "; Address stored in ip variable: 0xbfc601ac
cout << var << endl; Value of *ip variable: 20
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0; 49
}

By:- Prof. Prajakta Deepak Shetye


CALL BY POINTER
The call by pointer method of passing arguments to a function copies the address of an argument into the
formal parameter. Inside the function, the address is used to access the actual argument used in the call.
This means that changes made to the parameter affect the passed argument.
To pass the value by pointer, argument pointers are passed to the functions just like any other value.

50

By:- Prof. Prajakta Deepak Shetye


#include <iostream>

// function declaration
void swap(int *x, int *y);
// function definition to swap the values.
void swap(int *x, int *y) { int main () {
int temp; // local variable declaration:
temp = *x; /* save the value at address x */ int a = 100;
*x = *y; /* put y into x */ int b = 200;
*y = temp; /* put x into y */
cout << "Before swap, value of a :" << a << endl;
return; cout << "Before swap, value of b :" << b << endl;
}
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;
51
return 0;
}
By:- Prof. Prajakta Deepak Shetye
STRINGS
• C++ provides following two types of string representations −
1.The C-style character string.
2. The string class type introduced with Standard C++.

1.The C-style character string.


• This string is actually a one-dimensional array of characters which is terminated by a null character
'\0’.
• The following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than the
number of characters in the word "Hello.“
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0’};
If you follow the rule of array initialization, then you can write the above statement as follows −
char greeting[] = "Hello"; 52

By:- Prof. Prajakta Deepak Shetye


Following is the memory presentation of above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string when it initializes the array.

53

By:- Prof. Prajakta Deepak Shetye


#include <iostream.h>

void main ()
{

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

When the above code is compiled and executed, it produces the following result −

Greeting message: Hello


54

By:- Prof. Prajakta Deepak Shetye


FUNCTIONS
• strcpy(s1, s2); -- Copies string s2 into string s1.

• strcat(s1, s2); -- Concatenates string s2 onto the end of string s1.

• strlen(s1); -- Returns the length of string s1.

• strcmp(s1, s2); -- Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

• strchr(s1, ch); -- Returns a pointer to the first occurrence of character ch in string s1.

• strstr(s1, s2); -- Returns a pointer to the first occurrence of string s2 in string s1.

55

By:- Prof. Prajakta Deepak Shetye


#include <iostream>
#include <cstring>

void main () {

char str1[10] = "Hello";


char str2[10] = "World";
char str3[10]; strcpy( str3, str1) : Hello
int len ; strcat( str1, str2): HelloWorld
strlen(str1) : 10
strcpy( str3, str1); // copy str1 into str3
cout << "strcpy( str3, str1) : " << str3 << endl;

strcat( str1, str2); // concatenates str1 and str2


cout << "strcat( str1, str2): " << str1 << endl;

len = strlen(str1); // total lenghth of str1 after concatenation


cout << "strlen(str1) : " << len << endl;
56
}
By:- Prof. Prajakta Deepak Shetye
#include <iostream>
The String Class in C++ #include <string>
The standard C++ library
void main ()
provides a string class
{
type that supports all the
string str1 = "Hello";
operations mentioned
string str2 = "World";
above, additionally much
string str3;
more functionality. Let us
int len ;
check the following
example −
str3 = str1; // copy str1 into str3
cout << "str3 : " << str3 << endl;

str3 : Hello str3 = str1 + str2; // concatenates str1 and str2


str1 + str2 : HelloWorld cout << "str1 + str2 : " << str3 << endl;
str3.size() : 10
len = str3.size(); // total length of str3 after
concatenation
57
cout << "str3.size() : " << len << endl;

By:- Prof. Prajakta Deepak Shetye }


Object Oriented
Programming CLASS

ENCAPSULATI
INHERITANCE
ON

Object-oriented programming is a programming


paradigm based on the concept of "objects", OOPS
which can contain data and code: data in the form
of fields, and code, in the form of procedures. A DATA
ABSTRACTION
POLYMORPHI
SM
feature of objects is that an object's own
procedures can access and often modify the data
OBJECT
fields of itself.

58

By:- Prof. Prajakta Deepak Shetye


• OBJECTS :- Objects are the basic runtime entities.

• CLASS :- Class is way to bind data and its associated functions together.

• INHERITANCE :- Mechanism of deriving new class from an existing one.

• POLYMORPHISM :- Ability to take more than one form.

• DATA ABSTRACTION :- Partial hiding of data.

• ENCAPSULATION :- Total hiding of a data.

59

By:- Prof. Prajakta Deepak Shetye


CLASS
• A class is a way to bind data and its associated functions together.
• The entire set of data and code of an object can be made a user defined data type with the help of class.
• It allows the data (and functions) to be hidden, if necessary from external use.
• Generally, a class specification has two parts:
1. Class declaration 2. Class function definitions

The class declaration describes the type and scope of its members. The class function definitions describes
how class functions are implemented.

60

By:- Prof. Prajakta Deepak Shetye


For example, we defined the Box data type using the keyword class as follows −
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box Data Members
double height; // Height of a box

double getVolume(void); // Returns box volume Member function

};

61

By:- Prof. Prajakta Deepak Shetye


Class Access Modifiers
Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a
program to access directly the internal representation of a class type. The access restriction to the class members is
specified by the labelled public, private, and protected sections within the class body. The keywords public, private, and
protected are called access specifiers.
A class can have multiple public, protected, or private labelled sections. Each section remains in effect until either another
section label or the closing right brace of the class body is seen. The default access for members and classes is private.

• The public Members


A public member is accessible from anywhere outside the class but within a program.

• The private Members


A private member variable or function cannot be accessed, or even viewed from outside the class. Only the
class and friend functions can access private members.

• The protected Members


A protected member variable or function is very similar to a private member but it provided one additional
benefit that they can be accessed in child classes which are called derived classes. 62

By:- Prof. Prajakta Deepak Shetye


Scope Resolution Operator
Scope resolution operator is used to get the hidden names due to variable scopes so that you can still use
them. In C++, scope resolution operator is ( :: ).
Scope resolution operator in C++ can be used for:

• Accessing a global variable when there is a local variable with same name
• Defining a function outside a class
• Accessing a class’s static variables
• Referring to a class inside another class
• In case of multiple Inheritance

63

By:- Prof. Prajakta Deepak Shetye


MEMBER FUNCTION
• A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable. It operates on any object of the class of which it is a member, and has
access to all the members of a class for that object.
• Member functions can be defined within the class definition or separately using scope resolution
operator(::).
• Function can be defined at two places:-
1. Inside class function
2. Outside class function

64

By:- Prof. Prajakta Deepak Shetye


INSIDE CLASS
Defining a member function within the class definition declares the function inline, even if you do not
use the inline specifier. So either you can define Volume() function as below −

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

double getVolume(void)
{
return length * breadth * height;
}
};
65

By:- Prof. Prajakta Deepak Shetye


OUTSIDE CLASS
If you like, you can define the same function outside the class using the scope resolution operator (::) as
follows −

double Box::getVolume(void)
{
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before :: operator.

66

By:- Prof. Prajakta Deepak Shetye


Find area of circle using function Find area of circle using function
Find area of circle
#include<uostream.h> #include<uostream.h>
#include<iostream.h> #include<conio.h> #include<conio.h>
#include<conio.h>
Void areaofcircle(int); // function dec int areaofcircle(int); // function dec
Void main()
{ Void main() Void main()
int area, radius; { {
cout<<“Enter radius”; int radius; int area, radius;
cin>> radius;
cout<<“enter radius”; cout<<“enter radius”;
area= 3.14 * radius * radius; cin>> radius; cin>> radius;
cout<<“Area of circle is”<<radius; areaofcircle(radius); //function call area= areaofcircle(radius); //fu
cout<<“area of circle is”<<are
Getch(); Getch(); Getch();
} } }

Void areaofcircle(int r) // function def int areaofcircle(int r) // function67de


{ {
int area; int area;
By:- Prof. Prajakta Deepak Shetye area= 3.14 *r *r; area= 3.14 *r *r;
cout<<“area of circle is”<<area; return(area);
#include<iostream.h> void Circle :: display()
#include<conio.h> {
area= 3.14*radius*radius;
class Circle cout<<“Area of circle is”<<area;
{ }
public:
int area,radius; // data members
void getdata(); // member functions decl Void main()
void display(); {
}; Circle c1,c2,c3,c4;
c1.getdata(); // function call
void Circle :: getdata()
{
c1.display();
cout<<“Enter radius”;
Getch();
cin>>radius;
}
}

68

By:- Prof. Prajakta Deepak Shetye


#include<iostream.h>
#include<conio.h> Void main()
{
class Circle Circle c1; // object
{ c1.getdat();
public: c1.display();
int area,radius; // data members
Getch();
void getdata() // member functions }
{
cout<<“Enter radius”;
cin>>radius;
}

void display()
{
area= 3.14*radius*radius;
cout<<“Area of circle is”<<area;
}
69
};
By:- Prof. Prajakta Deepak Shetye
OBJECT
• An object is a variable whose datatype is a class.
• User can have more than one object for a class
• The object can be declared as
class-name oject1_name ,object2_name;
The declaration of object is similar to the basic variable.

Accessing members of class using objects

• The private data of a class can be accessed only through the member functions of that class using the
direct member access operator (.).

• The public data of a class can be accessed using the direct member access operator (.).

70

By:- Prof. Prajakta Deepak Shetye


#include <iostream.h>
// Member functions definitions
class Box
{ double Box::getVolume() 6.0 *7.0 *5.0
public: {
double length; // Length of a box return length * breadth * height;
double breadth; // Breadth of a box }
double height; // Height of a box
void Box::setLength( double len 12.0 )
// Member functions declaration {
length = len; 6.0
double getVolume(); }
void setLength( double len ); void Box::setBreadth( double bre 13.0)
void setBreadth( double bre ); {
void setHeight( double hei ); breadth = bre; 7.0
}; }
void Box::setHeight( double hei 10.0)
{
height = hei; 5.0 71
}
By:- Prof. Prajakta Deepak Shetye
// Main function for the program
// volume of box 1
Void main()
{ volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
Box Box1; // object1
Box Box2; // object2 // volume of box 2
double volume = 0.0; //variable volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// box 1 specification
}
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

72

By:- Prof. Prajakta Deepak Shetye


#include<iostream.h> class Circle Void main()
#include<conio.h> { {
private: Circle c1; //object
Void main() float radius, area; //data members
{ public:
float radius, area; c1.getdata();
void getdata() // 1st
member function c1.calculate();
cout<<“enter the radius”; { c1.print();
cin>>radius; cout<<“enter the radius”; }
cin>> radius;
area= 3.14*radius*radius; }

cout<<“area of circle is”<<area; void calculate() // 2nd member function


} {
area= 3.14*radius*radius;
}

void print() // 3rd member function


{
cout<<“Area of circle is”<<area; 73

}
};
By:- Prof. Prajakta Deepak Shetye
class Circle
void Circle :: getdata()
{
{
private: cout<<“enter the radius”;
float radius, area; //data member cin>>radius;
public: }
void getdata(); // 1st member function
void Circle :: calculate()
void calculate(); //2nd member function {
area=3.14*radius*radius;
void print(); //3 rd member function }
};
Void Circle ::print()
{
Void main() cout<<“Area of circle is”<<area’
{ }
Circle c1;

c1.getdata();
c1.calculate();
c1.print(); 74
}
By:- Prof. Prajakta Deepak Shetye
class Circle
{ Void main()
private: {
float radius, area; Circle c1;
public:
void getdata(float rad) c1.getdata(12.5);
{ c1.calculate();
radius=rad; c1.print();
} }

void calculate()
{
area= 3.14*radius*radius;
}

void print()
{
cout<<“Area of circle is”<<area;
75
}
};
By:- Prof. Prajakta Deepak Shetye
Class Simple
#include<iostream.h>
{
#include<conio.h>
double si,prin,rate,time;
Void main()
public:
{
void getdata(double p, double r, double t);
double si,prin,rate,time;
void calculate();
void display();
cout<<“Enter the values for prin, rate, time”;
};
cin>>prin>>rate>>time;
Void Simple::getdata(double p, double r, double t)
{
si=(prin*rate*time)/100;
prin=p;
rate=r;
cout<<“The simple interest is”<<si;
time=t;
}
Void main() }
{ void Simple:: calculate()
Simple s1; {
s1.getdata(5000.0,2.5,12.0); si=(prin*rate*time)/100;
S1.calculate(); }
S1.display(); void display()
} { 76
cout<<“Simple interest”<<si;
}
By:- Prof. Prajakta Deepak Shetye
FRIEND FUNCTION
A friend function of a class is defined outside that class' scope but it has the right to access all private and
protected members of the class. Even though the prototypes for friend functions appear in the class
definition, friends are not member functions.

A friend can be a function, or member function, or a class, in which case the entire class and all of its
members are friends. C++ called friend functions that break this rule and allow us to access member
functions from outside the class.

To declare a function as a friend of a class, precede the function prototype in the class definition with
keyword friend as follows –
class Box
{
double width;
public:
double length; 77
friend void printWidth( Box box );
By:- Prof. Prajakta Deepak Shetye
void setWidth( double wid );
};
NEED OF FRIEND FUNCTION

• By default : functions and data of a class are private to that class.


• Only the public members are accessible outside the class
• Protected members can be inherited along with public members.
• No such condition where private members can be accessed from outside the class.
• So friend functions and friend classes may be used where our application requires the access all the
members of a class.

78

By:- Prof. Prajakta Deepak Shetye


CHARACTERSTICS OF FRIEND
FUNCTION
• It is not in the scope of class to which it has been declared as friend.
• Since it is not in the scope of class, it cannot be called by using object of that class. It is called like a
normal c++ function.
• It can be declared either in public or private section without affecting its meaning.
• It has objects as arguments.
• It cannot access the member function directly and has to use an object name and dot operator with
each member name.

79

By:- Prof. Prajakta Deepak Shetye


#include<iostream.h> #include<iostream.h>
class A;
class A
class B {
{ private:
private: int val1;
int val2; public:
public: void get()
void getdata() {
{ val1=50;
val2=21; }
} void show()
void display() {
{ cout<<“Value of val1 is”<<val1;
cout<<“Value of val2 is”<<val2; }
} friend void exchange(B&, A&)
friend void exchange(B&, A&)
};
};
80

By:- Prof. Prajakta Deepak Shetye


void main()
{
GLOBAL FUNCTION A abc;
B pqr;

abc.get();
void exchange (B&x, A&y) pqr.getdata();
{
int temp; cout<<“Before exchange”;
temp= x.b;
x.b= y.a; abc.show();
y.a=temp; pqr.display();
}
exchange(abc,pqr);

cout<<“After exchange”;

abc.show();
pqr.display();
81
}

By:- Prof. Prajakta Deepak Shetye


Class Square; Class Square
{
Class Rectangle private:
{ int side;
private: public:
int width,height; void get()
public: {
void getdata() side=5;
{ }
width=20; friend void display(Rectangle &, Square &);
height=10; };
}
friend void display(Rectangle &, Square &); void main ()
}; {
Rectangle rec;
Square sq;
void display(Rectangle &r, Square &s)
{ rec.getdata();
cout << "Rectangle: " << r.width * r.height << endl; sq.get();
cout << "Square: " << s.side * s.side << endl;
} display(rec,sq);
82

}
By:- Prof. Prajakta Deepak Shetye
STATIC DATA MEMBER
• It is initialized to zero when the first object of its class is #include <iostream.h>
created. No other initialization is permitted. void Test()
{
• Only one copy of that member is created for entire class static int x = 1;
and is shared by all objects of that class, no matter how x = ++x;
many objects are created.
int y = 1;
• It is visible only within the class, but its lifetime is the
y = ++y;
entire program.
cout<<"x = "<<x<<"n";
cout<<"y = "<<y<<"n";
}
int main()
{
Test();
Test(); 83

return 0;
By:- Prof. Prajakta Deepak Shetye
}
int Example :: x;
#include <iostream.h>
void main()
class Example
{
{
Example obj1, obj2, obj3;
static int x;
public:
cout<<"Initial value of x" <<"n";
void function1()
{
obj1.function2();
x++;
obj2.function2();
}
obj3.function2();
void function2()
obj1.function1();
{
obj2.function1();
cout<<"x = "<<x<<"n";
obj3.function1();
}
};
cout<<"Value of x after calling function1"<<"n";

obj1.function2(); 84
obj2.function2();
By:- Prof. Prajakta Deepak Shetye
obj3.function2();
}
1 2 3
Static int
x=0

X++
X=1
X=2
X=3 x=3

85

By:- Prof. Prajakta Deepak Shetye


CONSTRUCTOR
• A class constructor is a special member function of a class that is executed whenever we create new objects
of that class.
• A constructor will have exact same name as the class and it does not have any return type at all, not even
void. Constructors can be very useful for setting initial values for certain member variables.
• A constructor is declared and defined as follow:-
Class Ratio
{
int m,n;
pubilc:
Ratio();
};

Ratio::Ratio()
86
{ m=1; n=2;
}
By:- Prof. Prajakta Deepak Shetye
CHARCTERISTICS
• The constructor name is all way same as class name.
• They do not have return type, not even void.
• They cannot be static or virtual.
• They should be declared in public section.
• They cannot be inherited though derived class can called base class constructor.
• They can have default arguments like c++ functions.
• We cannot refer to their address.
• When a constructor is declared for a class, initialization of class objects became mandatory, since
constructor is invoked automatically when the objects are created.

87

By:- Prof. Prajakta Deepak Shetye


TYPES OF CONSTRUCTOR
• Default constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.
• Parameterized constructor
These are the constructors with parameter. Using this Constructor you can provide different
values to data members of different objects, by passing the appropriate values as argument.
• Copy constructor
These are special type of Constructors which takes an object as argument, and is used to copy
values of data members of one object into other object.

88

By:- Prof. Prajakta Deepak Shetye


class Cube
{ DEFAULT
public: • In this case, as soon as the object is created the constructor is called which
int side; initializes its data members.
Cube()
{ • A default constructor is so important for initialization of object members,
side = 10; that even if we do not define a constructor explicitly, the compiler will
} provide a default constructor implicitly.
};
class Cube
{
void main() public:
{ int side;
OUTPUT };
Cube c; OUTPUT
10
cout << c.side; 0 or any random value
void main()
} {
Cube c;
cout << c.side; 89
}
By:- Prof. Prajakta Deepak Shetye
class Cube
{
PARAMETERIZED
public:
int side; CONSTRUCTORS
Cube(int x)
{
side=x;
} OUTPUT
}; 10
20
void main() 30
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
} 90

By:- Prof. Prajakta Deepak Shetye


class Simple Simple :: Simple(double p, double r, double t) // constructor
{ defined
double si, prin,rate, time; // data members {
prin=p;
public: rate=r;
time=t;
Simple(double p , double r, double t); // constructor }
void calculate(); // member function
void display(); // member function Void Simple :: calculate()
}; {
si=(prin* rate*time)/100;
Void main() }
{
clrscr(); Void Simple :: display()
{
Simple s1(2000.5, 2.5, 3.0); cout<<“Simple interest is “<<si;
s1.calculate(); }
s1.display();

getch();
} 91

By:- Prof. Prajakta Deepak Shetye


#include<iostream.h> Void Fibonacci::process() Void main()
#include<conio.h> { {
fib=f0+f1; int in;
Class Fibonacci f0=f1;
{ f1=fib; Fibonacci F;
private: } cout<<“ Enter number of elements”<<endl;
int f0,f1,fib; cin>>n;
Void Fibonacci::display() for(i=1;i<=n;i++)
public: { {
Fibonacci(); cout<<fib<<“\t”; F.process();
void process(); } F.display();
void display(); }
}; }

Fibonacci::Fibonacci()
{
f0=0;
f1=1;
}

92

By:- Prof. Prajakta Deepak Shetye


COPY CONSTRUCTOR
• Copy Constructor is a type of constructor which is used to create a copy of an already existing
object of a class type. It is usually of the form X (X&), where X is the class name. The compiler
provides a default Copy Constructor to all the classes.
• As it is used to create an object, hence it is called a constructor. And, it creates a new object,
which is exact copy of the existing copy, hence it is called copy constructor.

93

By:- Prof. Prajakta Deepak Shetye


void display()
#include<iostream.H> {
class Sample cout<<x<<" "<<y<<endl;
{ }
private: };
int x, y; //data members /* main function */
Void main()
public: {
Sample(int x1, int y1) Sample obj1(10, 15); // Normal constructor
{ Sample obj2 = obj1; // Copy constructor
x = x1; cout<<"Normal constructor : ";
y = y1; obj1.display();
} cout<<"Copy constructor : ";
obj2.display();
/* Copy constructor */ return 0;
Sample (const Sample &sam) }
{
x = sam.x;
y = sam.y; Normal constructor : 10 15
} Copy constructor : 10 15
94

By:- Prof. Prajakta Deepak Shetye


DESTRUCTOR
• Destructor is a special class function which destroys the object as soon as the scope of object ends. The
destructor is called automatically by the compiler when the object goes out of scope.
• The syntax for destructor is same as that for the constructor, the class name is used for the name of
destructor, with a tilde ~ sign as prefix to it.
• It can neither return a value nor can it take any parameters.
• Destructor can be very useful for releasing resources before coming out of the program like closing files,
releasing memories etc.
class A
{
public:
// defining destructor for class
~A()
{
// statement 95
}
};
By:- Prof. Prajakta Deepak Shetye
class A Void main()
{ {
// constructor A obj1; // Constructor Called
A() int x = 1
{ if(x)
cout << "Constructor called"; {
} A obj2; // Constructor Called
} // Destructor Called for obj2
// destructor } // Destructor called for obj1
~A()
{
cout << "Destructor called";
} OUTPUT:-
}; Constructor called
Constructor called
Destructor called
Destructor called
96

By:- Prof. Prajakta Deepak Shetye


OVERLOADING OF CONSTRUCTOR
Class interest
{ Void interest::process()
private: {
float amount, rate, total; total=amount+((rate*amount)/100);
public: cout<<“Total=“<<total;
interest() }
{
amount=2000.0 Void main()
rate=10.0; {
} interest i1,i2(500.0,5.0);
interest(float x, float y) cout<<“Default constructor”;
{ i1.process();
amount=x;
rate=y; cout<<“parameterized constructor”;
} i2.process();
97
void process(); }
};
By:- Prof. Prajakta Deepak Shetye
OPERATOR OVERLOADING
• The mechanism of giving some special meaning to an operator is called as operator overloading.
• Operator overloading provides a flexible option for the creation of new definitions for most of the
C++operators.
• When an operator is overloaded, its original meaning is not lost. For instance, the operator + has been
overloaded to add two vectors, can still be used to add two integers.
• To define an additional task to an operator a special function called operator function is used to specify
the relation of the operator to the class.

Return-type class-name :: operator op(argument list)


{
function body;
}
98

By:- Prof. Prajakta Deepak Shetye


RULES
• Only existing operators can be overloaded. New operators cannot be created.
• The overloaded operator must have at least one operand that is use of user-defined.
• The basic meaning of an operator cannot be changed.
• The overloaded operators follow the syntax rules of original operators.
• Following operators cannot be overloaded ( • , •*, : :, ?: )
• Unary operators overloaded through member function, take n0 explicit arguments.
• Binary operators overloaded by means of friend function, take two explicit arguments.
• Unary operators overloaded by means of friend function, take one reference arguments.
• Following operators cannot be overloaded by means of friend function( =, ( ), [ ], ->)

99

By:- Prof. Prajakta Deepak Shetye


class complex
complex complex :: operator+(complex &c) //operator overload
{
{
private: float x; //real
complex temp; //object
float y; //imaginary part
temp.x = x + c.x;
temp.y = y + c.y;
public:
return temp;
}
complex()
{}
void main()
{
complex(float real, float imag) //parameterized constructor
clrscr();
{
x=real;
y=imag; complex c1(2.5,3.5);
}
complex c2(1.1,1.7);
complex c3= c1+c2; //function call
complex operator+(complex &c);
cout<<"c1=";
void display()
c1.display();
{
cout<<"c2=";
cout<<x<<"+"<<y<<"i\n";
c2.display(); 10
} 0
cout<<"c3=";
};
c3.display();
By:- Prof. Prajakta Deepak Shetye
getch();
}
C1
X=2.5
Temp.x=x+c.x X=2.5 c.X=1.1 y=3.5
Temp.y=y+c.y Y=3.5 c.y=1.7

C2
X=1.1
y=1.7
C3=
C1+ c2

10
1

By:- Prof. Prajakta Deepak Shetye


#include <iostream>
using namespace std;
C++ allows us to convert data of one type to that of another.
This is known as type conversion. int main() {
There are two types of type conversion in C++. // assigning an int value to num_int
1.Implicit Conversion int num_int = 9;
2.Explicit Conversion (also known as Type Casting)
// declaring a double type variable
Implicit Type Conversion double num_double;
The type conversion that is done automatically done by the
compiler is known as implicit type conversion. This type of // implicit conversion
conversion is also known as automatic conversion. // assigning int value to a double variable
Output num_double = num_int;

num_int = 9 cout << "num_int = " << num_int << endl;


num_double = 9 cout << "num_double = " << num_double << endl;
In the program, we have assigned an int data to a double variable.
return 0;
num_double = num_int; }
Here, the int value is automatically converted to double by the 10
2
compiler before it is assigned to the num_double variable. This is an
example of implicit type conversion.
By:- Prof. Prajakta Deepak Shetye
INHERITANCE
• Inheritance allows us to define a class in terms of another class, which makes it easier to create and
maintain an application. This also provides an opportunity to reuse the code functionality and fast
implementation time.
• When creating a class, instead of writing completely new data members and member functions,
the programmer can designate that the new class should inherit the members of an existing class.
This existing class is called the base class, and the new class is referred to as the derived class.
• Inheritance is the process by which new classes called derived classes are created from existing
classes called base classes.
• The derived classes have all the features of the base class and the programmer can choose to add
new features specific to the newly created derived class.
10
3

By:- Prof. Prajakta Deepak Shetye


General Format for implementing the concept of Inheritance:

class derived_classname: access specifier base_classname


For example, if the base class is RATIO and the derived class is SAMPLE it is specified as:

class SAMPLE: public RATIO

The above makes SAMPLE have access to both public and protected variables of base class RATIO

class RATIO Base class


{
--------------------------------
---------------------- derived class
};

class SAMPLE : public RATIO


{
-------------------------------------
--------------------------------
10
}; Inheriting base class section 4

By:- Prof. Prajakta Deepak Shetye


Inheritance vs. Access
How inherited base class members
appear in derived class
Base class members
private: x private x is inaccessible
protected: y base class
private: y
public: z private: z

private: x protected x is inaccessible


protected: y base class protected: y
public: z protected: z

private: x public x is inaccessible


protected: y base class protected: y 10
5
public: z public: z
By:- Prof. Prajakta Deepak Shetye
Inheritance vs. Access
class Grade class Test : public Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
public class access, it looks like this: public members:
Test(int, int);
void setScore(float);
float getScore();
char getLetter(); 106
Inheritance vs. Access
class Grade class Test : protected Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
protected class access, it public members:
Test(int, int);
looks like this: protected members:
void setScore(float);
float getScore();
float getLetter();
107
Inheritance vs. Access
class Grade class Test : private Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
private class access, it void setScore(float);
float getScore();
looks like this: float getLetter();
public members:
Test(int, int);
108
// Derived class
// Base class
class Rectangle: public Shape
class Shape
{
{
public:
public:
int getArea()
void setWidth(int w)
{
{
return (width * height);
width = w;
}
}
};
void setHeight(int h)
{
Void main()
height = h;
{
}
Rectangle Rect;
protected:
int width;
Rect.setWidth(5);
int height;
Rect.setHeight(7);
};
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl; 109

}
By:- Prof. Prajakta Deepak Shetye
SHAPE CLASS

RECTANGLE CLASS

PUBLIC: SETWIDTH()
SETHEIGHT()
PUBLIC: GETAREA()
PROTECTED: WIDTH
HEIGHT

RECTANGLE CLASS
AFTER INHERIT
PUBLIC SECTION
GETAREA()
SETWIDTH()
SETHEIGHT()
11
0

By:- Prof. Prajakta Deepak Shetye


TYPES OF INHERITANCE
• 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.
• MULTIPLE INHERITANCE
- Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e one sub
class is inherited from more than one base classes.
• MULTILEVEL INHERITANCE
- In this type of inheritance, a derived class is created from another derived class.
• 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.
• HYBRID INHERITANCE
111
- Hybrid Inheritance is implemented by combining more than one type of inheritance.

By:- Prof. Prajakta Deepak Shetye


11
2

By:- Prof. Prajakta Deepak Shetye


MULTIPLE INHERITANCE

// Base class Shape // Base class PaintCost


class Shape class PaintCost
{ {
public: public:
void setWidth(int w) int getCost(int area)
{ {
width = w; return area * 70;
} }
void setHeight(int h) };
{
height = h; // Derived class
} class Rectangle: public Shape, public PaintCost
{
protected: public:
int width; int getArea()
int height; {
}; return (width * height); 113
}
};
By:- Prof. Prajakta Deepak Shetye
int main(void)
{
Rectangle Rect;
int area;

Rect.setWidth(5);
Rect.setHeight(7);

area = Rect.getArea();

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

// Print the total cost of painting


cout << "Total paint cost: $" << Rect.getCost(area) << endl;

return 0;
}

114

By:- Prof. Prajakta Deepak Shetye


Write a program in C++ to implement the following class hierarchy: Class student to obtain Roll Number,
Class Test to obtain marks scored in two different subjects, Class Sports to obtain weight-age (marks) in
sports and Class Result to calculate the total marks. The program must print the roll number, individual
marks obtained in two subjects, sports and total marks.

Class Student

Class Test Class Sports

115

Class Result
By:- Prof. Prajakta Deepak Shetye
class Student class Test : public Student
{ {
int roll_no; public:
float t1,t2;
public: void get_marks(float x,float y)
void get_no(int a) {
{ t1=x;
roll_no=a; t2=y;
} }
void put_no(void) void put_marks(void)
{ {
cout<<“Roll No:-”<<roll_n0; cout<<“Marks Obtained”<<t1<<”\t”<<t2<<endl;
} }
}; };

116

By:- Prof. Prajakta Deepak Shetye


class Sport class Result : public Test, public Sport
{ {
public: float total;
int score;
void get_score(int a) public:
{ void display(void)
score=a; {
} total=t1+t2+score;
void put_score(void) put_no();
{ put_marks();
cout<<“Sports Marks:- ”<<score<endl; put_score();
} cout<<”Total Marks Obtain:- \t“ <<total;
}; }

};

117

By:- Prof. Prajakta Deepak Shetye


void main()
{
Result res;

res.get_no(101);
res.get_marks(39,65);
Output:-
res.get_score(29);
Roll No:- 101
res.display();
Marks Obtain:- 39 65
Sports Marks:- 29
getch();
Total Marks Obtain:- 133
}

118

By:- Prof. Prajakta Deepak Shetye


POLYMORPHISM
• The word polymorphism means having many forms. Typically, polymorphism occurs when there is a
hierarchy of classes and they are related by inheritance.
• C++ polymorphism means that a call to a member function will cause a different function to be
executed depending on the type of object that invokes the function.
• 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
behaviour in different situations. This is called polymorphism.
• In C++ polymorphism is mainly divided into two types:
Compile time Polymorphism - This is also known as static (or early) binding.
Runtime Polymorphism - This is also known as dynamic (or late) binding.

119

By:- Prof. Prajakta Deepak Shetye


BASE
ANIMAL CLASS

ANIMALSOUND()

DERIVED 1 DERIVED 2
DOG CLASS PIG CLASS

ANIMALSOUND() ANIMALSOUND()
ANIMAL SOUND ANIMAL SOUND
() ()
12
0

By:- Prof. Prajakta Deepak Shetye


// Base class // Derived class
class Animal class Pig : public Animal
{ {
public: public:
void animalSound() void animalSound()
{ {
cout << "The animal makes a sound \n" ; cout << "The pig says: wee wee \n" ;
} }
}; };

// Derived class int main()


class Dog : public Animal {
{ Animal myAnimal;
public: Pig myPig;
void animalSound() Dog myDog;
{
cout << "The dog says: bow wow \n" ; myAnimal.animalSound();
} myPig.animalSound(); 12
1
}; myDog.animalSound();
By:- Prof. Prajakta Deepak Shetye
return 0;
}
COMPILE TIME
• Function overloading and Operator overloading are perfect example of Compile time polymorphism.
• In this example, we have two functions with same name but different number of arguments. Based on
how many parameters we pass during function call determines which function is to be called, this is
why it is considered as an example of polymorphism because in different conditions the output is
different. Since, the call is determined during compile time thats why it is called compile time
polymorphism.

122

By:- Prof. Prajakta Deepak Shetye


class Add Void main()
{ {
public: Add obj;
int sum(int num1, int num2)
{ //This will call the first function
return num1+num2; cout<<"Output: "<<obj.sum(10, 20)<<endl;
}
//This will call the second function
int sum(int num1, int num2, int num3) cout<<"Output: "<<obj.sum(11, 22, 33);
{
return num1+num2+num3; }
}
};

Output:
Output: 30
Output: 66 12
3

By:- Prof. Prajakta Deepak Shetye


RUN TIME
• Function overriding is an example of Runtime polymorphism.
• Function Overriding: When child class declares a method, which is already present in the parent class
then this is called function overriding, here child class overrides the parent class.
• In case of function overriding we have two definitions of the same function, one is parent class and one
in child class. The call to the function is determined at runtime to decide which definition of the
function is to be called, that’s the reason it is called runtime polymorphism.

124

By:- Prof. Prajakta Deepak Shetye


class A
{ void main()
public: {
void display()
{ //Parent class object
cout<<"Super Class Function"<<endl; A obj;
} obj.display();
};
//Child class object
class B: public A B obj2;
{ obj2.display();
public:
void display() }
{
cout<<"Sub Class Function";
}
}; Output:
12
Super Class Function 5
Sub Class Function
By:- Prof. Prajakta Deepak Shetye
VIRTUAL FUNCTION
• A virtual function is a member function which is declared within a base class and is re-
defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a
reference to the base class, you can call a virtual function for that object and execute the derived class’s
version of the function.
• Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for function call.
• They are mainly used to achieve Runtime polymorphism
• Functions are declared with a virtual keyword in base class.
• The resolving of function call is done at Run-time.

12
6

By:- Prof. Prajakta Deepak Shetye


• Rules for Virtual Functions
1. Virtual functions cannot be static and also cannot be a friend function of another class.
2. Virtual functions should be accessed using pointer or reference of base class type to achieve run time
polymorphism.
3. The prototype of virtual functions should be same in base as well as derived class.
4. They are always defined in base class and overridden in derived class. It is not mandatory for derived
class to override (or re-define the virtual function), in that case base class version of function is used.
5. A class may have virtual destructor but it cannot have a virtual constructor.

12
7

By:- Prof. Prajakta Deepak Shetye


class base
class derived : public base
{
{
public:
public:
virtual void print()
void print()
{
{
cout << "print base class" << endl;
cout << "print derived class" << endl;
}
}
void show()
void show()
{
{
cout << "show base class" << endl;
cout << "show derived class" << endl;
}
}
};
};

12
8

By:- Prof. Prajakta Deepak Shetye


void main() Runtime polymorphism is achieved only through a pointer (or
{ reference) of base class type. Also, a base class pointer can
base* bptr; point to the objects of base class as well as to the objects of
derived class. In above code, base class pointer ‘bptr’ contains
derived d;
the address of object ‘d’ of derived class.
bptr = &d;

// virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();
}

Output:

print derived class


show base class
12
9

By:- Prof. Prajakta Deepak Shetye


WORKING WITH FILES
• 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 topic 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.
• Files are used to store data in a storage device permanently. File handling provides a mechanism to store
the output of a program in a file and to perform various operations on it.
• A stream is an abstraction that represents a device on which operations of input and output are
performed. A stream can be represented as a source or destination of characters of indefinite length
depending on its usage.

13
0

By:- Prof. Prajakta Deepak Shetye


OUTPUT STREAM DISK FILE

INPUT STREAM
TO HANDLE ALL INPUT AND OUTPUT OPERTION WE NEED
TO INCLUDE fstream.h HEADER FILE IN ALL FILE
HANDLING PROGRAM.

PROGRAM
13
1

By:- Prof. Prajakta Deepak Shetye


FILE HANDLING CLASSES

13
2

By:- Prof. Prajakta Deepak Shetye


• In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.
• ofstream: This data type represents the output file stream and is used to create files and to write
information to files.
• ifstreamThis data type represents the input file stream and is used to read information from files.
• fstream: This data type represents the file stream generally, and has the capabilities of both 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.

• C++ provides us with the following operations in File Handling:


1. Creating a file: open()
2. Reading data: read()
3. Writing new data: write()
4. Closing a file: close()
13
3

By:- Prof. Prajakta Deepak Shetye


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.

13
4

By:- Prof. Prajakta Deepak Shetye


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.

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 ); 13
5

By:- Prof. Prajakta Deepak Shetye


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

13
6

By:- Prof. Prajakta Deepak Shetye


WRITING AND READING A FILE
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.

13
7

By:- Prof. Prajakta Deepak Shetye


// close the opened file.
#include <fstream> outfile.close();
#include <iostream>
// open a file in read mode.
void main () ifstream infile;
{ infile.open("afile.dat");
char data[100];
cout << "Reading from the file" << endl;
// open a file in write mode. infile >> data;
ofstream outfile;
outfile.open("afile.dat"); // write the data at the screen.
cout << data << endl;
cout << "Writing to the file" << endl;
cout << "Enter your name: "; // again read the data from the file and display it.
cin.getline(data, 100); infile >> data;
cout << data << endl;
// write inputted data into the file.
outfile << data << endl; // close the opened file.
infile.close();
cout << "Enter your age: ";
cin >> data; } 13
cin.ignore(); 8
outfile << data << endl;
By:- Prof. Prajakta Deepak Shetye
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara 9

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.

13
9

By:- Prof. Prajakta Deepak Shetye


eof ( ) Function
This function determines the end-of-file by returning true(non-zero) for end of file otherwise returning
false(zero).

Syntax

Stream_object.eof( );

Example :
fout.eof( );

14
0

By:- Prof. Prajakta Deepak Shetye


Text File Functions
get() – read a single character from text file and store in a buffer.

e.g file.get(ch);

put() - writing a single character in textfile

e.g. file.put(ch);

getline() - read a line of text from text file store in a buffer.

e.g file.getline(s,80);

We can also use file>>ch for reading and file<<ch writing in text file. But >> operator does not accept
white spaces.

14
1

By:- Prof. Prajakta Deepak Shetye


Write a program in C++ to read the name of a country from one text file and name of its corresponding capital
city from another text file. The program must display the country name and indicate its corresponding capital
(for at least five countries) in the output
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
clrscr();
char str1[80],str2[80];
ofstream fout;
ifstream fin1,fin2;
fout.open("country.txt");
fout<<"INDIA\nUSA\nUK\nRUSSIA\nJAPAN";
14
fout.close(); 2

By:- Prof. Prajakta Deepak Shetye


fout.open("capital.txt");
fout<<"NEW DELHI\nWASHINGTON D.C\nLONDON\nMOSCOW\nTOKYO";
fout.close();
cout<<"COUNTRY\t\tCAPITAL\n";
cout<<"-------------------------\n";
fin1.open("country.txt");
fin2.open("capital.txt");
while(!fin1.eof() && !fin2.eof())
{
fin1.getline(str1,80);
fin2.getline(str2,80);
cout<<str1<<"\t\t"<<str2<<"\n";
}getch();
14
} 3

By:- Prof. Prajakta Deepak Shetye

You might also like