Object Oriented Programming (210243) SE Computer Engineering

Download as pdf or txt
Download as pdf or txt
You are on page 1of 254

Bhujbal Knowledge City

MET Institute of Engineering

Object Oriented Programming[210243]


SE Computer Engineering
UNIT-I
Fundamentals of Object Oriented Programming

By
Ms. Vaishali Khandave
Assistant Professor
Computer Engineering

03/09/2020 OOP 1
SE Syllabus

Syllabus_SE_2019_Course

03/09/2020 OOP 2
Unit Contents
Introduction to object-oriented programming, Need of object-
oriented programming, Fundamentals of object-oriented
programming: Namespaces, objects, classes, data members,
methods, messages, data encapsulation, data abstraction and
information hiding, inheritance, polymorphism. Benefits of OOP,
C++ as object oriented programming language.
C++ Programming- C++ programming Basics, Data Types,
Structures, Enumerations, control structures, Arrays and Strings,
Class, Object, class and data abstraction, Access specifiers,
separating interface from implementation.
Functions- Function, function prototype, accessing function and
utility function, Constructors and destructor, Types of constructor,
Objects and Memory requirements, Static members: variable and
functions, inline function, friend function
03/09/2020 OOP 3
Introduction to OOP paradigm

➢ Object-oriented programming (OOP) is a


programming paradigm based on the concept of
"objects", which can contain data, in the form of
fields (often known as attributes or properties), and
code, in the form of procedures (often known
as methods or functions).

03/09/2020 OOP 4
Introduction to Procedure-Oriented
Programming
➢ Emphasis is on doing things (algorithms).
➢ Large programs are divided into smaller programs
known as functions.
➢ Most of the functions share global data.
➢ Data move openly around the system from function to
function.
➢ Functions transform data from one form to another.
➢ Employs top-down approach in program design.

03/09/2020 OOP 5
Procedure-Oriented Programming

Relationship of data and functions in POP

03/09/2020 OOP 6
Limitations of Procedural Programming
➢ The program code is harder to write
➢ The Procedural code is often not reusable, which may
pose the need to recreate the code if is needed to use
in another application
➢ Difficult to relate with real-world objects
➢ The importance is given to the operation rather than
the data, which might pose issues in some data-
sensitive cases
➢ The data is exposed to the whole program, making it
not so much security friendly

03/09/2020 OOP 7
Object-Oriented Programming Benefits

➢ OOP mimics the real world, making it easier to


understand
➢ OOP codes are reusable in other programs
➢ Security is offered due to the use of data hiding and
abstraction mechanism
➢ Due to modularity and encapsulation, OOP offers
ease of management

03/09/2020 OOP 8
OOP Paradigms

Organization of Data and Functions in OOP


03/09/2020 OOP 9
Fundamentals of object oriented
Programming
Namespaces:
➢ A namespace is a declarative region that provides a scope
to the identifiers (the names of types, functions, variables,
etc) inside it.
➢ Namespaces are used to organize code into logical groups
and to prevent name collisions that can occur especially
when your code base includes multiple libraries.
➢ eg. using namespace std;
Here std is the namespace where ANSI C++ standard class
libraries are defined.

03/09/2020 OOP 10
Fundamentals of object oriented
Programming
➢Defining namespace
syntax-
namespace namespace_name
{
// code declarations
}

03/09/2020 OOP 11
Fundamentals of object oriented
Programming
#include <iostream>
using namespace std;
// first name space
namespace first_space
{
void func() {
cout << "Inside first_space" << endl;
}
}
// second name space
namespace second_space
{
void func() {
cout << "Inside second_space" << endl;
}
}

03/09/2020 OOP 12
Fundamentals of object oriented
Programming
int main ()
{
// Calls function from first name space.
first_space::func();

// Calls function from second name space.


second_space::func();

return 0;
}

03/09/2020 OOP 13
Fundamentals of object oriented
Programming
Objects:
➢ Objects are the basic run time entities in an object-
oriented system.
➢ When a program is executed, the objects interact by
sending messages to one another.
➢ Objects take up space in the memory.
➢ We can create ‘n’ number of objects belonging to
particular class.

03/09/2020 OOP 14
Object Example
class example
{
-------
-------
};
int main()
{
example obj; //object of class example
}

03/09/2020 OOP 15
Fundamentals of object oriented
Programming
Classes:
➢ 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.

03/09/2020 OOP 16
Fundamentals of object oriented
Programming
➢ Classes:

03/09/2020 OOP 17
Fundamentals of object oriented
Programming
Data Members:
➢ Data members include members that are declared
with any of the fundamental types, as well as other
types, including pointer, reference, array types, bit
fields, and user-defined types.

03/09/2020 OOP 18
Fundamentals of object oriented
Programming
Data Members:

03/09/2020 OOP 19
Fundamentals of object oriented
Programming
Methods:
➢ Methods are functions that belongs to the class.
➢ There are two ways to define functions that belongs
to a class:
– Inside class definition.
– Outside class definition.

03/09/2020 OOP 20
Inside class definition
class example
{
public:
void add() //method defined inside class
{
------
------
}
};

Int main()
{
example obj;
obj.add();
return 0;
}

03/09/2020 OOP 21
Outside class definition
class example
{
public:
void add() //method declared inside class
};

void example::add() //method defined outside class


{
------
------
}

Int main()
{
example obj;
obj.add();
return 0;
}
03/09/2020 OOP 22
Fundamentals of object oriented
Programming
Messages:
➢ Objects communicate with one another by sending
and receiving information to each other.
➢ A message for an object is a request for execution of
a procedure and therefore will invoke a function in
the receiving object that generates the desired results.
e.g. employee.salary(name)
(object) (Message) (information)

03/09/2020 OOP 23
Fundamentals of object oriented
Programming
Data Encapsulation:
➢ Encapsulation is an Object Oriented Programming
concept that binds together the data and functions
that manipulate the data, and that keeps both safe
from outside interference and misuse.

03/09/2020 OOP 24
Fundamentals of object oriented
Programming
➢ Data Abstraction refers to providing only
essential information to the outside world
and hiding their background details, i.e., to represent
the needed information in program without
presenting the details.
➢ Data hiding is an object-oriented programming
technique of hiding internal object details
i.e. data members.

03/09/2020 OOP 25
Fundamentals of object oriented
Programming

03/09/2020 OOP 26
Fundamentals of object oriented
Programming
➢ Inheritance is a process in which one object acquires
all the properties and behaviors of its parent object
automatically.
➢ In C++, the class which inherits the members of
another class is called derived class and the class
whose members are inherited is called base class.

03/09/2020 OOP 27
Types Of Inheritance

03/09/2020 OOP 28
Fundamentals of object oriented
Programming
Polymorphism:
➢ The word polymorphism means having many forms.
➢ In simple words, we can define polymorphism as the ability of
a message to be displayed in more than one form.
➢ A person at the same time can have different characteristics.
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.
➢ It takes place when there is a hierarchy of classes and they are
related by inheritance.

03/09/2020 OOP 29
Fundamentals of object oriented
Programming
Types of Polymorphism

03/09/2020 OOP 30
Benefits of OOP

➢ Modularity for easier troubleshooting


➢ Reuse of code
➢ Flexibility through polymorphism
➢ Effective problem solving
➢ Security
➢ Code maintenance

03/09/2020 OOP 31
C++ As OOP Language

➢ C++ is called object oriented programming (OOP)


language because C++ language views a problem in
terms of objects involved rather than the procedure
for doing it.
➢ Object oriented programming is always good for
writing large business logics and large applications or
games.
➢ OOPs is also very much desired for maintenance and
long term support.

03/09/2020 OOP 32
Introduction to C++
➢ C++ is an Object Oriented Programming Language
➢ It was developed by Bjarne Stroustrup at AT & T
(American Telephone & Telegraph) Bell Lab in USA
in 1980.
➢ Wanted to combine simula67 and C
➢ Class is a major addition to the original C language,
he initially called the new language ‘C with classes’.
➢ Later in 1983 the name was changed to C++.
➢ The idea of C++ comes from the C increment
operator ++, therefore C++ is an incremented version
of C.
➢ C++ is a superset of C. Whatever in C is applies to
03/09/2020 OOP 33
C++
Continued…
➢ C++ is an object-oriented programming language, so
it is safer and well-structured programming language
than C
➢ Let's see the programming languages that were
developed before C++ language.
Language Year Developed By

Algol 1960 International Group


BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis
Ritchie
C++ 1980 Bjarne Stroustrup
03/09/2020 OOP 34
Simple C++ Program
#include<iostream>
using namespace std;
int main()
{
cout<<“Hello World”;
return 0;
}

03/09/2020 OOP 35
Continued…
#include<iostream>: This directive causes the
pre-processor to add the contents of the iostream
file

It is input output stream, means it contains the


declaration for the identifier cout, cin, operator
<< (bitwise left shift operator), >> (bitwise right
shift operator) respectively.

03/09/2020 OOP 36
Continued….
Common header files used in C++ programming
are:
<iostream>
<iomanip>
<fstream>
<cmath>
<cstring>
<cstdlib>

03/09/2020 OOP 37
Continued….
Namespace: This defines the scope for the
identifiers that are used in a program

std: is the namespace where ANCI C++ standard


class libraries are defined

using and namespace: are the new keywords in


C++

03/09/2020 OOP 38
Continued….
Return type of main():Every main in C++
should end with return 0 statement
The default return type for all the functions in
C++ is int.

int main() main()


{ {
return 0; return 0;
} }
03/09/2020 OOP 39
Continued….
If function does not return any value, then return
type for main() is specified as void()
void main()
{

03/09/2020 OOP 40
Continued….
Output Operator: In C++ for printing or
displaying purpose we need cout and operator
<<
e.g. cout<<“Enter the Numbers:”;
The identifier cout is a predefined object that
represents the standard output stream in C++.
Standard output stream represents the screen.
The operator << is called as insertion or put to
operator.
It inserts or sends the contents of the variable on
its right to the object on its left
03/09/2020 OOP 41
Continued….
Input Operator: In C++ for reading the data
we need cin and operator >>
e.g. cin>>a;
The identifier cin is a predefined object that
represents the standard input stream in C++.
Standard input stream represents the
keyboard.
The operator >> is called as extraction or get
from operator.
It extracts or takes the value from the keyboard
and assigns it to the variable on its right.
03/09/2020 OOP 42
Comments in C++
The double slash comment is a single line
comment
//Welcome to
// Department of Computer Engineering

The Multiline comments can be written as


/* Welcome to
Department of Computer Engineering */

03/09/2020 OOP 43
Cascading of input and output operators
The multiple use of << or >> in one statement is
called cascading.

e.g. cin>>a;
cin>>b;

Above 2 statements can be written in one


statement as
cin>>a>>b;
03/09/2020 OOP 44
Editors used for C++ Program

➢ Dev C++: Dev C++ can be used only on Windows, it


doesn’t support other OSs such as Linux and OS X.
➢ Visual Studio Code:Visual Studio Code is a modern,
open-source IDE developed by Microsoft. It’s
available for Windows, Linux, and macOS.
➢ Code::Blocks: this IDE on various platforms such as
Windows, Mac OS X, and Linux.
➢ Eclipse:This is an open-source IDE that is available
for Windows, Mac OS X, and Linux.

03/09/2020 OOP 45
Continued…
➢ Code Lite: CodeLite is a powerful code editor that
supports Windows, OS X, and Linux. It’s open-source
software, meaning it’s free of cost.
➢ Netbeans: This is also open source software
➢ Qt Creator:Qt Creator is a useful C++ IDE for
building GUI-based cross-platform software
applications for mobile, desktop, embedded devices,
etc.
• you can build high-quality graphical user-interfaces
and high-performance applications and speed up your
developme
03/09/2020 OOP 46
Continued…

➢ Along with all above editors sublime Text, Atom,


Brackets are also the editors which can be used for
development of C++ program
Example:
1. Addition of numbers
Case 1: without any value
Case 2: by constant value
Case 3: by user

2. Area of circle (declaration


03/09/2020 OOP
of variable as int, float) 47
Control Structures in C++
Three types of control structures:
1. Sequence structure (straight line)
2. Selection structure (branching)
3. Loop structure (iteration or repetition)

All program processing can be coded by using only


these three logic structures.
Like C, C++ also supports all these three basic control
structure and implements them using various control
statements

03/09/2020 OOP 48
Continued….
Control
Structures

Selection Sequence Loop

If…else switch Do…while While, for

03/09/2020 OOP 49
Control Structures
1. if statement: The C++ if statement tests the
condition. It is executed if condition is true.

if(condition)
{
//code to be executed
}

03/09/2020 OOP 50
Continued….

03/09/2020 OOP 51
Continued….
#include <iostream>
using namespace std;
int main ()
{
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}

03/09/2020 OOP 52
Continued…..
if…else statement: The C++ if-else statement also tests
the condition. It executes if block if condition is true
otherwise else block is executed.

if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
03/09/2020 OOP 53
}
Continued…..

03/09/2020 OOP 54
Continued…
#include <iostream>
using namespace std;
int main ()
{
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}
03/09/2020 OOP 55
Continued…..
if…else if ladder statement
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
else{
//code to be executed if all the conditions are false
}
03/09/2020 OOP
56
Continued…..

03/09/2020 OOP
57
Continued…
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter the a,b,c:";
cin>>a>>b>>c;
if(a>b && a>c)
{
cout<<"a is greater";
}
else if (b>c && b>a)
{
cout<<"b is greater";
}
else
{
cout<<"c is greater";
}
return 0;
03/09/2020 OOP 58
}
Continued…..
2. switch statement: It executes one statement from multiple
conditions
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
03/09/2020
//code to be executed
OOP
if all cases are not matched;
59
Continued…..

03/09/2020 OOP
60
#include <iostream>
using namespace std;
int main ()
{
int num;
cout<<"Enter a number to check grade:";
cin>>num;
switch (num)
{
case 10: cout<<"It is 10";
break;
case 20: cout<<"It is 20";
break;
case 30: cout<<"It is 30";
break;
default: cout<<"Not 10, 20 or 30";
break;
} return 0;
03/09/2020 OOP 61
}
Continued…..
3. while loop: In C++, while loop is used to iterate a
part of the program several times. If the number of
iteration is not fixed, it is recommended to use while
loop than for loop. It is an entry controlled loop.

while(condition)
{
//code to be executed
}

03/09/2020 OOP 62
Continued…..

03/09/2020 OOP 63
Continued…
#include <iostream>
using namespace std;
int main()
{
int i=1;
while(i<=10)
{
cout<<i <<"\n";
i++;
}
return 0;
}

03/09/2020 OOP 64
Continued…..
4. do while loop: The C++ do-while loop is used to
iterate a part of the program several times. If the number
of iteration is not fixed and you must have to execute
the loop at least once, it is recommended to use do-
while loop. It is an exit controlled loop.

do
{
//code to be executed
}
while(condition);
03/09/2020 OOP 65
Continued…..

03/09/2020 OOP 66
Continued…
#include <iostream>
using namespace std;
int main()
{
int i = 1;
do
{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
return 0;
}

03/09/2020 OOP 67
Continued…..
5. for loop: The C++ for loop is used to iterate a part of
the program several times. If the number of iteration is
fixed, it is recommended to use for loop than while or
do-while loops. It is also an entry controlled loop.

for(initialization; condition; incr/decr)


{
//code to be executed
}

03/09/2020 OOP 68
Continued…..

03/09/2020 OOP 69
Continued…
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++)
{
cout<<i <<"\n";
}
return 0;
}

03/09/2020 OOP 70
break Statement in C++
The C++ break is used to break loop or switch statement. It
breaks the current flow of the program at the given condition. In
case of inner loop, it breaks only inner loop.

Syntax:
jump-statement;
break;

03/09/2020 OOP 71
Continued…

03/09/2020 OOP 72
Continued…
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
cout<<i<<"\n";
}
return 0;
}
03/09/2020 OOP 73
Continued…

Output of above program

1
2
3
4

03/09/2020 OOP 74
Continued…
The C++ break statement breaks inner loop only if you use
break statement inside the inner loop.

#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
break;
}
cout<<i<<" "<<j<<"\n";
}
} return 0;
} 03/09/2020 OOP 75
Continued…

Output of above program

11
12
13
21
31
32
33

03/09/2020 OOP 76
Continued…
#include <iostream>
using namespace std;
int main()
{
int number;
int sum = 0;
while (true)
{
cout << "Enter a number: "; // take input from the user
cin >> number; // break condition
if (number < 0)
{
break;
}
// add all positive numbers
sum += number;
} // display the sum
cout << "The sum is :" << sum << endl;
return 0;
}03/09/2020 OOP 77
Continued…

Output of above program

Enter a number:2
Enter a number:3
Enter a number:1
Enter a number:-1
The sum is :6

03/09/2020 OOP 78
continue Statement in C++
The C++ continue statement is used to continue loop. It continues
the current flow of the program and skips the remaining code at
specified condition. In case of inner loop, it continues only inner
loop.

Syntax:

jump-statement;
continue;

03/09/2020 OOP 79
Continued…
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
cout<<i<<"\n";
}
}

03/09/2020 OOP 80
Continued…

Output of above program

1
2
3
4
6
7
8
9
10
03/09/2020 OOP 81
Continued…
C++ Continue Statement continues inner loop only if you use
continue statement inside the inner loop.
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
continue;
}
cout<<i<<" "<<j<<"\n";
}
}
03/09/2020 OOP 82
}
Continued…

Output of above program

11
12
13
21
23
31
32
33

03/09/2020 OOP 83
➢ break statement: the break statement terminates the smallest
enclosing loop (i. e., while, do-while, for or switch statement)
➢ continue statement: the continue statement skips the rest of the
loop statement and causes the next iteration of the loop to take
place.

03/09/2020 OOP 84
Continued…
#include <iostream>
using namespace std;
main()
{
int i;
cout << "The loop with break produces output as: \n";

for (i = 1; i <= 5; i++) {

// Program comes out of loop when


// i becomes multiple of 3.
if ((i % 3) == 0)
break;
else
cout << i << " ";
}
cout << "\nThe loop with continue produces output as: \n";
for (i = 1; i <= 5; i++) {

// The loop prints all values except


// those that are multiple of 3.
if ((i % 3) == 0)
continue;
cout << i << " ";
03/09/2020 } OOP 85
}
Continued…

Output of above program


The loop with break produces output as:
12
The loop with continue produces output as:
1245

03/09/2020 OOP 86
Continued…
When any code block contains only one line the braces can be
omitted. This applies to any control structure: if, while, for,
do-while

But if contains more than one lines or bunch of lines then there
must be curly braces, otherwise it will execute only the first
statement after the brace and all other lines are omitted.

03/09/2020 OOP 87
goto statement in C++
➢ The C++ goto statement is also known as jump statement. It is
used to transfer control to the other part of the program. It
unconditionally jumps to the specified label.
➢ It can be used to transfer control from deeply nested loop or
switch case label.

03/09/2020 OOP 88
Continued…
#include <iostream>
using namespace std;
int main()
{
ineligible:
cout<<"You are not eligible to vote!\n";

cout<<"Enter your age:\n";


int age;
cin>>age;
if (age < 18)
{
goto ineligible;
}
else
{
cout<<"You are eligible to vote!";
}
return 0;
} 03/09/2020 OOP 89
Tokens
The smallest individual units in a program are known as
tokens.
C++ has following tokens
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators

A C++ program is written using these tokens, white


spaces and the syntax of the language.

03/09/2020 OOP 90
Keywords
The keywords are the special symbols.

The keyword is a reserved word.

The keywords can not be used as variable names,


constant name or other user defined program
elements.

In C, 32 keywords are there but C++ contain more than


32.

03/09/2020 OOP 91
Continued…
A list of 32 Keywords in C++ Language which are
also available in C language are given below.

auto break case char const continue default do


double else enum extern float for goto if
int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

03/09/2020 OOP 92
Continued…
A list of 30 Keywords in C++ Language which are
not available in C language are given below.

asm dynamic_cast namespace reinterpret_cast bool


explicit new static_cast false catch
operator template friend private class
this inline public • throw const_cast
delete mutable protected true try
typeid typename using virtual wchar_t

03/09/2020 OOP 93
Identifiers
Identifiers refers to the name of the variables,
functions, arrays, classes or other user-defined data
types created by the programmer.

Identifiers are the fundamental requirement of any


language.

Each Language has its own rules for naming these


identifiers

03/09/2020 OOP 94
Continued…
Some naming rules are common in both C and C++.
They are as follows:
➢ Only alphabetic characters, digits, and underscores are
allowed.
➢ The identifier name cannot start with a digit, i.e., the
first letter should be alphabetical. After the first letter,
we can use letters, digits, or underscores.
➢ In C++, uppercase and lowercase letters are distinct.
Therefore, we can say that C++ identifiers are case-
sensitive.
➢ A declared keyword cannot be used as a variable
name.
03/09/2020 OOP 95
Continued…
Examples:
MetBkc and Metbkc are two different identifiers as C++
is a case sensitive.

Second, Test1 , _area, num are the examples of valid


identifiers

While following are the examples of invalid


identifiers
• Avg-1 // containing special character '-'.
• 2sum // the first letter is a digit.
•03/09/2020
break // use of a keyword.
OOP 96
Continued…
Note:
The major difference between C and C++ is the limit on
the length of the name of the variable. ANSI C considers
only the first 32 characters in a name while ANSI C++
imposes no limit on the length of the name.

03/09/2020 OOP 97
Continued…
#include <iostream>
using namespace std;
int main()
{
int no;
int NO;
cout<<"Enter the values of ‘no' and ‘NO'";
cin>>no;
cin>>NO;
cout<<"The values that you have entered are : "<<no<<" , "<<NO
;
return 0;
}
03/09/2020 OOP 98
Continued…
In the above code, we declare two variables ‘no' and
‘NO'. Both the words are same but they will behave as
different identifiers. As we know that the identifiers are
the case-sensitive so both the identifiers will have
different memory locations.

03/09/2020 OOP 99
Differences between Identifiers and Keywords
Identifiers Keywords
Identifiers are the names defined by the Keywords are the reserved words whose
programmer to the basic elements of a meaning is known by the compiler.
program.
It is used to identify the name of the It is used to specify the type of entity.
variable.
It can consist of letters, digits, and It contains only letters.
underscore.
It can use both lowercase and uppercase It uses only lowercase letters.
letters.
No special character can be used except the It cannot contain any special character.
underscore.
The starting letter of identifiers can be It can be started only with the lowercase
lowercase, uppercase or underscore. letter.
It can be classified as internal and external It cannot be further classified.
identifiers.
03/09/2020
Examples are test, result, sum, power, etc. 100
Examples are 'for', 'if', 'else', 'break', etc.
OOP
Constants
Constants refers to fixed values that do not change
during the execution of program.

C++ supports several kinds of literal constants. They


include integer, characters, floating point numbers
and strings.

Literal constant do not have memory locations.

03/09/2020 OOP 101


Constants
Examples:

30 -decimal integer
40.12 – floating point number
037 – Octal integer
0X2 – hexadecimal integer
“MET” - string constant
‘A’ – character constant

03/09/2020 OOP 102


Operators in C++
An operator is simply a symbol that is used to perform
operations.

Types of Operators:

1. Arithmetic Operators
+, -, *, /, % are the binary operators

++, -- are the unary operators

?: are the tertiary/ ternary/conditional operator


03/09/2020 OOP 103
Continued…
2. Relational Operators
>, <, >=, <=, ==, !=

3. Logical Operators
&&, ||

4. Bitwise Operators
&, | , <<, >>, ~ , ^

5. Assignment Operators
=, += , -= , *= , /= , %=
03/09/2020 OOP 104
New Operators in C++
<< insertion operator
>> extraction operator
:: scope resolution operator
::* pointer to member declarator
->* pointer to member operator
.* pointer to member operator
: visibility operator
. To access data member from class
-> To access data member using pointer
delete memory release operator
endl new line character or line feed operator
new memory allocation operator
setw
03/09/2020 field width operator
OOP 105
C++ Data Types

03/09/2020 OOP 106


Built-in Data Types
Both C and C++ compiler support all the built-in data types.

It is also known as basic or fundamental data types.

The memory size of basic data types may change according to 16,
32 or 64 bit operating system.

Let's see the basic data types. It size is given according to 16 bit
OS.

03/09/2020 OOP 107


Built-in Data Types
Data Types Memory Size Range
char 1 byte -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 255
short 2 byte -32,768 to 32,767
signed short 2 byte -32,768 to 32,767
unsigned short 2 byte 0 to 32,767
int 2 byte -32,768 to 32,767
signed int 2 byte -31,768 to 32,767
unsigned int 2 byte 0 to 65535
short int 2 byte -31,768 to 32,767
signed short int 2 byte -32,768 to 32,767
unsigned short int 2 byte 0 to 65535
long int 4 byte -2147483648 to 2147483647
signed long int 4 byte -2147483648 to 2147483647
unsigned long int 4 byte 0 to 4294967295
float 4 byte 3.4E-38 to 3.4E+38
double 8 byte 1.7E-308 to 1.7E+308
03/09/2020 long double 10 byte OOP3.4E-4932 to 1.1E+4932 108
void Built-in Data Types
Two uses of void are
1. To specify the return type of a function when it is
not returning any value.
2. To indicate an empty argument list to a function
e.g. void fun(void);

03/09/2020 OOP 109


User Defined Data Types
1. Structures
Structures provide a method for packing together data of different
data types.
A structure is a convenient tool for handling a group of logically
related data items.

struct student
{
char name[20];
int roll_no;
float total_marks;
};

03/09/2020 OOP 110


User Defined Data Types
The keyword struct declares student as a new data type that can
hold three fields of different data types. These fields are known as
structure member or elements. (e.g. name, roll_no, total marks)

The identifier student, which is referred as structure name or


structure tag can be used to create variables of type student
e.g. struct student A;

A is a variable of type student and has three member variables as


defined by the template. Member variables can be accessed using
the dot or period operator as follows.
strcpy(A.name, “MET”);
A.roll_no=12;
A.total_marks=700;
03/09/2020 OOP 111
User Defined Data Types
Structure can have arrays, pointers as members

Features of C++ structures


1. In C++ , a structure can have both variables and functions as
members. It can also declare some of its members as ‘private’
so that they can not be accessed directly by the external
functions.
2. It attempts to bring the user defined data types as close as
possible to the built-in data types and also provides a facility
of data hiding and inheritance
3. In C++, the structure name are stand alone and can be used
like any other type names means the keyword struct can be
omitted in the declaration of structure variables.
e.g. student A;
03/09/2020 OOP 112
User Defined Data Types
2. class
All the features of C++ structures are available in another user
defined data type known as class.
Most of the C++ programmers tend to use the structures for
holding the data and classes to hold both data and functions.
Syntax:
class classname
{
private: variable declaration;
function declaration;
public:
variable declaration;
function declaration;
}03/09/2020 OOP 113
User Defined Data Types
Note:

The only difference between a structure and class in C++ is that,


by default the members of a class are private, while by default
the member of a structure are public.

03/09/2020 OOP 114


User Defined Data Types
Enumeration:
➢ 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.

03/09/2020 OOP 115


User Defined Data Types
Properties of 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

03/09/2020 OOP 116


User Defined Data Types
Example:

#include <iostream>
using namespace std;
enum week { Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday, Sunday };
int main()
{
week day;
day = Friday;
cout << "Day: " << day+1<<endl;
return 0;
}
03/09/2020 OOP 117
Derived Data Types
Arrays:

Arrays in C++ is similar to that in C


The only exception is the way character arrays are initialized.
When initializing a character array in ANSI C, the compiler will
allow us to declare the array size as the exact length of the string
constant
e.g. char string[3]= “BKC”; is valid in C

Here it is assume to leave out the null character \0 in the


definition.
But in C++, the size should be one larger than the number of
characters in the string.
e.g. char string[4]=“BKC”; in C++
03/09/2020 OOP 118
Derived Data Types
Like other programming languages, array in C++ is a group of
similar types of elements that have contiguous memory location.
In C++, array index starts from 0. We can store only fixed set of
elements in C++ array.

03/09/2020 OOP 119


Derived Data Types
Types of Arrays:
There are two types of arrays in C++

1. Single Dimensional Array


2. Multidimensional Array

03/09/2020 OOP 120


Derived Data Types
1. Single Dimensional Array
#include <iostream>
using namespace std;
int main()
{
int arr[5]={50,40,30,20,10}; //creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}

03/09/2020 OOP 121


Derived Data Types
Taking the values form user
#include <iostream>
using namespace std;
int main()
{
int a[5],i;
cout<<"Enter the array values:";
for(i=0;i<5;i++)
{
cin>>a[i];
}
cout<<"Displaying the array values:\n";
for(i=0;i<5;i++)
{
cout<<a[i]<<"\n"; //new line at each row
}
return 0;
}

03/09/2020 OOP 122


Derived Data Types
Taking the array size at run time
#include <iostream>
using namespace std;
int main()
{
int a[100],i,n;
cout<<"Enter the value of n:";
cin>>n;
cout<<"Enter the array values:";
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"Displaying the array values:\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\n"; //new line at each row
}
return 0;
}3/09/2020
0 OOP 123
Derived Data Types
Using #define

#include <iostream>
# define size 5
using namespace std;
int main()
{
int a[size],i,n;
cout<<"Enter the array values:";
for(i=0;i<size;i++)
{
cin>>a[i];
}
cout<<"Displaying the array values:\n";
for(i=0;i<size;i++)
{
cout<<a[i]<<"\n"; //new line at each row
}
return 0;
} 03/09/2020 OOP 124
Derived Data Types
2. Multidimensional Array
multidimensional array in C++ which declares, initializes and
traverse two dimensional arrays.
A 2D array is a C++ variable which has a name, a type, and a
pair of dimensions, which we might symbolize as m and n.
The first dimension is known as the row index, and the second
as the column index. Often, the names i and j are used for typical
row and column indexes.

03/09/2020 OOP 125


Derived Data Types
2. Multidimensional Array
multidimensional array in C++ which declares, initializes and
traverse two dimensional arrays.
#include <iostream>
using namespace std;
int main()
{
int a[3][3],i,j;
cout<<"Enter the array values:";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>a[i][j];
}
}
cout<<"Displaying the array values:\n";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
03/09/2020 OOP 126
}
Derived Data Types
2. Multidimensional
Array int test[3][3]; //declaration of 2D array
test[0][0]=5; //initialization
test[0][1]=10;
test[1][1]=15;
test[1][2]=20;
test[2][0]=30;
test[2][2]=10; OR
int test[3][3] =
{
{2, 5, 5},
{4, 0, 3},
{9, 1, 8} };
03/09/2020 OOP 127
Derived Data Types
2. Multidimensional
#include <iostream>
using namespace std;
int main()
{
int test[3][3]; //declaration of 2D array
test[0][0]=5; //initialization
test[0][1]=10;
test[1][1]=15;
test[1][2]=20;
test[2][0]=30;
test[2][2]=10;
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
03/09/2020 OOP 128
}
Derived Data Types
Output of above program is

5 10 0
0 15 20
30 0 10

03/09/2020 OOP 129


Derived Data Types
2. Multidimensional
#include <iostream>
using namespace std;
int main()
{
int test[3][3] =
{
{2, 5, 5},
{4, 0, 3},
{9, 1, 8} }; //declaration and initialization
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}03/09/2020 OOP 130
Derived Data Types
Output of above program is

2 5 5
4 0 3
9 1 8

03/09/2020 OOP 131


Derived Data Types
Functions:

➢ In C++, functions have major changes.


➢ Many of these modifications and improvements were driven
by the requirements of the object oriented concept of C++.
➢ All the features of C++ functions are read under the heading
“Functions in C++” later on

03/09/2020 OOP 132


Derived Data Types
Pointers:

The pointer in C++ language is a variable, it is also known as


locator or indicator that points to an address of a value.
Pointer is a variable in C++ that holds the address of another
variable.

Address Value

Pointer Variable

03/09/2020 OOP 133


Derived Data Types
Usage of Pointers:
There are many usage of pointers in C++ language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using
malloc() and calloc() functions where pointer is used.
In C++ language, we can dynamically allocate memory using
new operator where pointer is used.

2) Arrays, Functions and Structures


Pointers in C++ language are widely used in arrays, functions and
structures. It reduces the code and improves the performance.

03/09/2020 OOP 134


Derived Data Types
Symbol used in pointer

DeDE
Symbol Name Description

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


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

Declaring a pointer

int *a; //pointer to int


char *c; //pointer to char

03/09/2020 OOP 135


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

03/09/2020 OOP 136


Derived Data Types
Example:

int *ip; //int pointer


ip=&x; //address of x assigned to ip
*ip=10; //10 assigned to x through indirection

C++ adds the concept of constant pointer and pointer to a constant


char *const ptr=“GOOD”;
We can not modify the address that ptr is initialized to

int const *ptr1=&m;


ptr1 is declared as pointer to a constant. It can point to any variable
of correct data type, but the contents of what it points to can not be
changed
03/09/2020 OOP 137
Derived Data Types
We can also declare both pointer and the variable as constant in the
following way

const char *const cp=“xyz”;

This statement declares cp as a constant pointer to the string which


has been declared a constant
In this case, neither the address assigned to the pointer cp nor the
contents it points to can be changed.

Pointers are used in C++ for memory management and achieving


polymorphism.

03/09/2020 OOP 138


Declaration of variables
➢ In C all variables must be declared before they are used in
executable statements. This is true with C++ also.

➢ There is difference between C and C++ regarding the place of


variable declaration in the program.

➢ C requires all the variables to be defined at the beginning of a


scope although their actual use appears elsewhere in the scope,
sometimes far away from the place of declaration.

➢ In C before using a variable we should go back to the beginning of


the program to see whether it has been declared and what type.

03/09/2020 OOP 139


Declaration of variables
➢ In C++, we can declare the variables anywhere in the scope.

➢ This means that a variable can be declared right at the place of its
first use.

Advantages:
➢ This makes the program much easier to write

➢ This reduces the errors that may be caused by having to scan back
and forth.

➢ It also makes the program easier to understand as the variables are


declared in the context of their use
03/09/2020 OOP 140
Declaration of variables
#include <iostream>
using namespace std;
int main()
{
int sum=0;
for(int i=1;i<=5;i++)
{
sum=sum+i;
}
cout<<"Sum is="<<sum<<"\n";
float avg;
avg=sum/5;
cout<<"Average is="<<avg;
return 0;
}
03/09/2020 OOP 141
Dynamic initialization of variables
C++ allow the initialization of variables at run time. This is called as dynamic
initialization.

In C++, a variable can be initialized at run time using expressions at the place
of declaration.

e.g. int n=strlen(string);


Float area=3.14*rad*rad;

Thus both declaration and initialization of a variable can be done


simultaneously at the place where the variable is used for the first time,

The two statements in above example


float avg;
avg=sum/5;
Can be combined into single statement
03/09/2020 OOP 142
float avg=sum/5;
Reference variables
A reference variable provides an alias (alternative name) for a previously
defined variable.

Syntax: datatype &reference_name= variable name;


e.g. If we make the variable sum a reference to the variable total, then sum and
total can be used interchangeably to represent that variable.

float total=100;
float &sum=total;

total is a float type variable that has already been declared; sum is the
alternative name declared to represent the variable total. Both the variables
refer to the same data object in the memory.

The statements
cout<<total;
03/09/2020
and cout<<sum; both
OOP
print the value 100 143
Reference variables
The statement
total=total+10; will change the value of both total and sum to 110.

Likewise the assignment


sum=0;
Will change the value of both the variables to zero.

A reference variable must be initialized at the time of declaration

Note: Here & is not an address operator. The notation float & means
reference to float.

03/09/2020 OOP 144


Reference variables
Other examples are:
int n[10];
int &x= n[10]; //x is alias for n[10]
char &a=‘\n’; // initialize reference to a literal

int x;
int *p=&x;
int &m=*p;
Here the declaration causes m to refer to x which is pointed to by the pointer p

int &n=50;
This statement creates an int object with value 50 and name n

03/09/2020 OOP 145


Memory Management Operators
We use dynamic allocation techniques when it is not known in advance how
much of memory space is needed.

C uses malloc() and calloc() functions to allocate memory dynamically at run


time.

Also C uses the function free() to free dynamically allocated memory.

C++ defines two unary operators new and delete that perform the task of
allocating and freeing the memory

Since these operators manipulate memory on the free store, they are also
known as free store operators.

An object can be created by using new and destroyed by using delete as &
when required.
03/09/2020 OOP 146
Memory Management Operators
new operator
Syntax:
pointer_variable= new datatype;

First we declared the pointer as


int *p;
float *q;
Here p and q must have been declared as pointer of appropriate types.

Here pointer_variable is a pointer of type data type. The data type may be
any valid data type.
e.g. p =new int;
q= new float;
Where p is a pointer of data type int and q is a pointer of data type float

03/09/2020 OOP 147


Memory Management Operators
We can combine the declaration of pointers and their assignment as follows
int *p=new int;
float *q=new float;

The statements
*p=25; *q=7.5;
Assigns 25 to the newly created int object and 7.5 to the float object

We can initialize the memory using new operator as follows


pointer_variable= new datatype(value);
Here value specifies the initial value.
e.g. int *p= new int(25);
float *q= new float(8);

03/09/2020 OOP 148


Memory Management Operators
New can be used to create a memory space for any data type including user
defined types such as arrays, structure and classes.
The syntax for one dimensional array is:
pointer_variable= new datatype[size];
Here size specifies the number of elements in the array.
e.g. int *p=new int[10];
Creates a memory space for an array of 10 integers. P[0] refers to first element
and so on.
When creating multidimensional arrays with new, all the array sizes must be
supplied.
array_ptr= new int[3][5][4]; //legal
array_ptr= new int[m][5][4]; //legal
array_ptr= new int[3][5][]; //illegal
array_ptr= new int[][5][4]; //illegal

03/09/2020 OOP 149


Memory Management Operators
delete operator

When a data object is no longer needed, it is destroyed to release the


memory space for reuse.

Syntax:
delete pointer_variable;

The pointer variable is the pointer that points to a data object created
with new.
e.g. delete p;
delete q;

03/09/2020 OOP 150


Memory Management Operators
If we want to free a dynamically allocated array, then we use the following
syntax

delete [size] pointer_variable;

Here the size specifies the number of elements in the array to be freed, but the
problem with this is that we should remember the size of the array.

So, another syntax is

delete [] pointer_variable;

e.g. delete[] p;
Will delete the entire array pointed by p.

03/09/2020 OOP 151


Type Cast Operators
C++ permits explicit type conversion of variables or expressions using the type
cast operator

In ‘C’;
Syntax:
(datatypename)expression
e.g. average=sum/(float)i;

In ‘C++’
Syntax:
datatypename(expression)
e.g. average=sum/float(i)

03/09/2020 OOP 152


Functions in C++
Functions play an important role in C++ program development.

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.

Dividing a program into function is one of the major principles of


top-down, structured programming

03/09/2020 OOP 153


Functions in C++
Advantage of functions in C
1) 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.

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

03/09/2020 OOP 154


Functions in C++
Types of Functions
There are two types of functions in C programming:
Functions

User Defined
Library Function Function

1. Library Functions: are the functions which are declared in the


C++ header files such as ceil(x), cos(x), exp(x), etc.

2. 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
03/09/2020
of a big program andOOPoptimizes the code. 155
Functions in C++
void display( ); // function declaration

main()
{
……………..
display();
……………..
} // function call

void display()
{
……………..
} // function body
03/09/2020 OOP 156
Functions in C++
When the function is called, control is transferred to the first
statement in the function body.
The other statements in the function body are then executed and
control returns to the main program when the closing brace is
encountered.
C++ has added many new features to function to make them more
reliable and flexible.

03/09/2020 OOP 157


Functions in C++
Function Prototyping:
Function prototype is a declaration statement in the calling
program.

Syntax:
datatype function_name(argument list);

The argument list contains the datatype and names of arguments


that must be passed to the function.

e.g. float volume(int x, float y, float z);

Each argument variable must be declared independently inside the


parentheses.
03/09/2020 OOP 158
Functions in C++
e.g. float volume(int x, float y, z); is not allowed.

In a function declaration the names of arguments are dummy


variables and so they are optional.

So we can write,
float volume(int, float, float)
is valid at the place of declaration, because at this stage, the compiler
only checks for the type of arguments when the function is called.
It mean we can either include or exclude the variable name in the
program while declaring the function.
The variable names in the declaration just act as placeholders &
therefore if names are used, they don’t have to match the names used
in the function call or function definition.
03/09/2020 OOP 159
Functions in C++
Function Definition:
In the function definition, names are required, because the arguments
must be referenced inside the function.

e.g. float volume(int a, float b, float c)


{
float v= a*b*c;
}

03/09/2020 OOP 160


Functions in C++
Function Call:
We can call the function volume() as,

e.g. float cube1= volume(b1, w1, h1)

The variable b1,w1,h1 are known as actual parameters which specify


the dimension of cube1.
In the function call, function should not include the data type names
in the argument list
Their data types(which have been declared earlier) should match with
the datatypes declared in the prototype.

03/09/2020 OOP 161


Functions in C++
Another way to declare a function
We can also declare a function with an empty argument list

e.g. void display();


In C++, this means that the function does not pass any parameters,
we can also write this is as
void display(void);

A C++ function can also have an ‘open’ parameter list by the use of
ellipses in the prototype as shown below:

void abc(…);

03/09/2020 OOP 162


Functions in C++
C++ Function Passing types:

The arguments passed to a function can be performed in two ways:


1] Passed by value
2] Passed by reference

03/09/2020 OOP 163


Functions in C++
1] Passed by value
Arguments passed by value are the copies of the values of variables
and are passed to the function
#include <iostream>
using namespace std;
int test(int, int);
int main()
{
int b;
int s=5, u=6;
b=test(s,u);
cout<<"b="<<b;
return 0;
}
int test(int x, int y)
{
int z;
z=x+y;
return z;
03/09/2020 OOP 164
}
Functions in C++
Thus, the copies of the values 5 & 6 are passed to the function
definition & not the variables s and u. Any changes in the variable x
and y would not have any effect or change the variable s and u.

03/09/2020 OOP 165


Functions in C++
2] Passed by Reference
The symbol used for denoting the passed by reference is & (ampersand)
#include <iostream>
using namespace std;
int test(int &, int &);
int main()
{
int x=5, y=4;
test(x,y);
cout<<"The output is:\n";
cout<<"Value of x="<<x<<"\n";
cout<<"Value of y="<<y<<"\n";
return 0;
}
int test(int &s, int &u)
{
s=s*10;
u=u*10;
}

03/09/2020 OOP 166


Functions in C++
Here, two integer variables x and y are defined in the calling
function, the main program with values x=5 and y=4.

The variables x &y are passed to the called function test where it
is associated with variables s and u.

Whatever changes were made in the variable s & u effect or


reflect on the variables x & y respectively and vice versa.

In the above program, the function multiplied the value of


variable s & u by 10 which is reflected in the variable x & y.

03/09/2020 OOP 167


Functions in C++
So, when a variable is passed by reference, it passes the variable to
the function definition and not the copies of the value. Any
changes to the variable in the function definition would effect or
reflect corresponding changes in the variables passed as reference.

In this case, it has not returned any value by using return


statement. By using the concept of passing by reference, it is
possible to return more than one value.

03/09/2020 OOP 168


Functions in C++
Return By Reference
A function can also return a reference
e.g.
int &max(int &x, int &y)
{
if(x>y)
return x;
else
return y;
}
Since the return type of max() is int&, the function return reference
to x or y (and not the values). Then a function call such as max(a,b)
will yield a reference to either a or b depending on their values.
03/09/2020 OOP 169
Functions in C++
Default arguments:
➢ C++ can call a function without specifying all its arguments.
➢ In such a case, the function assigns a default value to the
parameter which does not have a matching argument in the
function call.
➢ Default values are specified when the function is declared.
➢ The compiler looks at the prototype to see how many arguments
a function uses and alerts the program for possible default values.
e.g.
float price(float p, int q, float r=0.15); // fun declaration
The syntax of default value is similar to the variable initialization.

We call this function as


value=price(5000,7); //one argument missing
03/09/2020 OOP 170
Functions in C++
It passes the value 5000 to p, 7 to q and function use default value
of 0.15 for r

e.g. value=price(5000,7,0.12);
Passes an explicit value of 0.12 to r.

A default argument is checked for datatype at the time of


declaration and evaluated at the time of call.

03/09/2020 OOP 171


Functions in C++
Only the trailing arguments can have default values and therefore
we must add defaults from right to left.

e.g. int add(int i; int j; int k=10);


int add(int i; int j=5; int k=10);
int add(int i=0; int j; int k=10);
int add(int i=5; int j);
int add(int i=2; int j=5; int k=10);

Adv:
We can use default arguments to add new parameters to the
existing functions.
Default arguments can be used to combine similar functions into
one.
03/09/2020 OOP 172
Functions in C++
Const arguments:
In C++, an argument to a function can be declared as const as
shown below
e.g. int length(const string &s);
int strlen(const char *p);

The qualifier const tells the compiler that the function should not
modify the argument

If we change or modify the argument, then the compiler will


generate an error.

This type of declaration is significant only when we pass


arguments by reference or pointers.
03/09/2020 OOP 173
Classes
➢ It is useful for defining and classification
➢ Every class in object oriented programming is collection of
data and function which is responsible to generate number of
objects.
➢ Each object is associated with the data of type class with
which they are created.
➢ A class is thus a collection of objects of similar datatype
➢ E.g.fruit class, animal class, human being,bank etc.
➢ Classes are user defined data types and behave like built-in
types of programming language.

03/09/2020 OOP 174


Objects
➢ Every object is run time entity which utilizes the features of
class by calling data and function.
➢ It is an instance (copy) of class.
➢ E.g. Apple is a object of class fruit
Account holder is a object of class bank
Dog is a object of class animal.

03/09/2020 OOP 175


Object Communication

03/09/2020 OOP 176


Object Communication
➢ An object oriented program consist of set of objects
that communicate with each other.
➢ Object communication with one another by sending
and receiving information much the same way as
people pass messages to one another.
➢ Message passing involves the specifying the name of
object, the name of the function (message) and the
information to be sent

03/09/2020 OOP 177


Continued….
Class specification has two parts:
1. Class declaration
2. Class function definitions

03/09/2020 OOP 178


Continued….
The general form of a class declaration is
class classname
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};

03/09/2020 OOP 179


Continued….
➢ Every class should be declared with a reserved word class.
➢ The body of a class is enclosed within braces and terminated by a
semicolon.
➢ The class body contains the declaration of variables and functions.
➢ These functions and variables are collectively called as class
members.
➢ They are usually grouped under two sections, namely, private and
public to denote which of the members are private and which of
them are public.
➢ The keywords private and public are known as visibility labels and
access specifiers.
➢ These private, public, protected keywords are always followed by
colon.
➢ By default, the members of a class private.
➢ The variables declared inside the class are known as data members
an functions are known as member
03/09/2020 OOP functions. 180
Continued….
Access Specifiers:
They are used to identify access rights for the data and member
functions of the class.
Three main types of access specifiers.
1. private: A private member within a class denote that only
members of the same class have accessibility. The private
members are inaccessible from outside the class.
2. public: A public members are accessible from outside the
class.
3. protected: A protected access specifier is a stage between
private and public access. If member functions defined in a
class are protected, they can not be accessed from outside the
class but can be accessed from the derived class.

03/09/2020 OOP 181


Continued….
Data hiding in classes: Only the member function can have access
to private data members and private functions. However the public
members(both functions and data) can be accessed from outside the
class

03/09/2020 OOP 182


Continued…
#include <iostream>
using namespace std;

class student
{
private: int rno,m1,m2,m3,m4,m5,total;
char name[20];
float percent;
public:
void getdata();
void result();
void showdata();
};

void student::getdata()
{
cout<<"Enter roll no:"<<endl;
cin>>rno;
cout<<"Enter name:"<<endl;
cin>>name;
cout<<"ENter marks in 5 subjects:"<<endl;
cin>>m1>>m2>>m3>>m4>>m5;
}
03/09/2020 OOP 183
void student::result()
{
total=m1+m2+m3+m4+m5;
percent=total/5.0;
}

void student::showdata()
{
cout<<"Roll No="<<rno<<endl;
cout<<"Name="<<name<<endl;
cout<<"Total="<<total<<endl;
cout<<"Percentage="<<percent<<endl;
}

int main()
{
student s; // it allocates a memory of....bytes
s.getdata();
s.result();
s.showdata();

return 0;
}03/09/2020 OOP 184
➢ Create a class circle to print area & circumference for two
different objects

➢ Create class bank with following details acno, acname, actype,


opening balance. Perform following by testing at least for two
objects
Open account
Withdraw
Deposit
Show current balance

03/09/2020 OOP 185


Class using prototyped function with parameter

#include <iostream>
using namespace std;

class math
{
private: int no1,no2;
public:
void setdata(int,int);
void showdata();
int product();
int addition();
int substraction();
};

void math::setdata(int i,int j)


{
no1=i;
no2=j;
}

int math::product()
{
return(no1*no2);
}

03/09/2020 OOP 186


int math::substraction()
{
return(no1-no2);
}

int math::addition()
{
return(no1+no2);
}

void math::showdata()
{
int p=product();
int a=addition();
int s=substraction();
cout<<"No1="<<no1<<endl;
cout<<"No2="<<no2<<endl;
cout<<"Addition="<<a<<endl;
cout<<"Substraction="<<s<<endl;
cout<<"Product="<<p<<endl;

int main()
{
math m; // it allocates a memory of....bytes
m.setdata(50,10);
m.showdata();

return 0;
03/09/2020 OOP 187
}
Continued….
Arrays of objects
Whenever we create number of objects within memory, then
instead of storing them randomly within memory, it is better to
hold them within sequence, commonly known as group or array
because of which we have following advantage.
1. Since objects are stored within sequence we can very easily
search by using index.
2. Operations such as sorting, searching, intersection etc.
becomes more simplified than normal approach.
3. We can add dynamic nature by creating dynamic array.

03/09/2020 OOP 188


Continued….
C++ supports 2 types of object array
1. Static array: array of objects with fixed size. Compile time
memory allocation.
e.g. student s[5];
Limitation: fixed length, can’t be extended or shrinked

2. Dynamic array: array of objects with varying size, run time


memory allocation.
e.g. student *s;
How many students..? Let us say it is ‘n’
s= new student[n];

03/09/2020 OOP 189


Static array of objects
#include <iostream>
using namespace std;

class employee
{
private:
float salary;
char name[10],dept[10];

public:
void get();
void show();
};

void employee::get()
{
cout<<"Enter the name:"<<endl;
cin>>name;
cout<<"Enter the salary:"<<endl;
cin>>salary;
cout<<"Enetr the department:"<<endl;
cin>>dept;
}

03/09/2020 OOP 190


void employee::show()
{
cout<<"Employee Name:"<<name<<endl;
cout<<"Employee salary:"<<salary<<endl;
cout<<"Employee dept:"<<dept<<endl;
}

int main()
{
employee e[5];
for(int i=0;i<5;i++)
{
e[i].get();
}

cout<<"employee information is";

for(int i=0;i<5;i++)
{
e[i].show();
}
return 0;
}

03/09/2020 OOP 191


Dynamic array of objects
#include <iostream>
using namespace std;

class employee
{
private:
float salary;
char name[10],dept[10];

public:
void get();
void show();
};

void employee::get()
{
cout<<"Enter the name:"<<endl;
cin>>name;
cout<<"Enter the salary:"<<endl;
cin>>salary;
cout<<"Enetr the department:"<<endl;
cin>>dept;
}

03/09/2020 OOP 192


void employee::show()
{
cout<<"Employee Name:"<<name<<endl;
cout<<"Employee salary:"<<salary<<endl;
cout<<"Employee dept:"<<dept<<endl;
}

int main()
{
employee *e; int n;
cout<<“How many employees information you want:”;
cin>>n;
e=new employee[n];
for(int i=0;i<n;i++)
{
e[i].get();
}

cout<<"employee information is";

for(int i=0;i<n;i++)
{
e[i].show();
}
return 0;
03/09/2020 OOP 193
}
Constructors
➢ A constructor is a special member function whose task is to
initialize the objects of it’s class.
➢ The constructor is invoked whenever an object of its
associated class is created.
➢ It is called constructor because it constructs the values of data
members of the class.

03/09/2020 OOP 194


Constructors
Characteristics of Constructor:
➢ Constructor has same name as that of the classname.
➢ They should be declared in the public section.
➢ They are called/invoked automatically when the objects are created.
➢ They do not have return types , not even void and therefore they can
not return values.
➢ They can not be inherited, though a derived class can tell the base
class constructor.
➢ Like other C++ functions, they can have default arguments.
➢ Constructors can not be virtual.
➢ We can not refer to their addresses.
➢ An object with a constructor can not be used as a member of union.
➢ They make ‘implicit calls’ to the operators new and delete when
memory allocation is required.
03/09/2020 OOP 195
Constructors
Syntax:
classname(arguments)
{
……………;
……………;
}

03/09/2020 OOP 196


Constructors
#include <iostream>
using namespace std;

class bank
{
int p,q;
public:
bank();
};

bank::bank()
{
p=500;
q=700;
}

int main()
{
bank b1,b2;
return 0;
}

03/09/2020 OOP 197


Constructors
Here objects b1,b2 are created of type bank and it initializes its
data members p and q to 500 & 700 respectively.

There is no need to write any statement to call the constructor


function as we do with the normal member functions.

In case of normal functions, we need to call /invoke that function


for each objects separately. This would be very inconvenient, if
there are a large number of objects.

03/09/2020 OOP 198


Constructors
Types of Constructors

03/09/2020 OOP 199


Constructors
1. Default Constructor
A constructor that accepts no parameters is called the default
constructor

Syntax:
classname( )
{
……………;
……………;
}

03/09/2020 OOP 200


Constructors
2. Parameterized Constructor
A constructor that can take arguments is called as parameterized
constructor

Syntax:
classname( argument list)
{
……………;
……………;
}

03/09/2020 OOP 201


Constructors
3. Copy Constructor
A constructor can accept a reference to its own class as a
parameter which is called as copy constructor

Syntax:
classname( classname &object)
{
……………;
……………;
}

03/09/2020 OOP 202


#include <iostream>

using namespace std;

class Rectangle
{
private:
int length,width,area,peri;
public:
Rectangle(); //default constructor
Rectangle(int,int); //parameterized constructor
Rectangle(Rectangle &robj); //copy constructor
void cal();
void show();
};

Rectangle::Rectangle()
{
length=2;
width=3;
}

Rectangle::Rectangle(int l,int w)
{
length=l;
width=w;
}

Rectangle::Rectangle(Rectangle &robj)
{
length=robj.length;
width=robj.width;
area=robj.area;
peri=robj.peri;
}

03/09/2020 OOP 203


void Rectangle::show()
{
cout<<"Length is="<<length<<endl;
cout<<"Width is="<<width<<endl;
cout<<"Area is="<<area<<endl;
cout<<"Perimeter is="<<peri<<endl;
}

void Rectangle::cal()
{
area=length*width;
peri=2*(length+width);
}

03/09/2020 OOP 204


int main()
{
Rectangle r1(10,20);
cout<<"First Rectangle is:"<<endl;
r1.cal();
r1.show();

Rectangle r2;
cout<<"Second Rectangle is:"<<endl;
r2.cal();
r2.show();

Rectangle r3(r1);
// Rectangle r3=r1;

//but r3=r1 is not valid


cout<<"Third Rectangle is:"<<endl;
r3.show();
return 0;
}

03/09/2020 OOP 205


Output

First Rectangle is:


Length is=10
Width is=20
Area is=200
Perimeter is=60

Second Rectangle is:

Length is=2
Width is=3
Area is=6
Perimeter is=10

Third Rectangle is:


Length is=10
Width is=20
Area is=200
Perimeter is=60

03/09/2020 OOP 206


Constructors
Calling Constructors
Every constructor can be called by using 2 methods

1. Implicit call: It is instant call which is provided as soon as


object is declared.
Syntax: Rectangle r1(10,20);

2. Explicit call: A constructor can be called after declaring


object.
Syntax: Rectangle r1;
r1= Rectangle (10,20);

03/09/2020 OOP 207


Constructors
Constructor with default arguments:
It is possible to define constructors with default arguments

e.g. complex(float real, float imag=0);

Then, the statement


complex p(5.0);
Assigns the value 5.0 to the real variable and 0.0 to imag (by
default)
However the statement
complex p(5.0, 2.0);
Assigns 5.0 to real and 2.0 to imag. The actual parameters, when
specified overrides the default value.
03/09/2020 OOP 208
Destructors
➢ Whenever objects are created, they occupy some memory
space. If we do not destroy the object, the memory will remain
allocated to them.

➢ Therefore, for the efficient utilization of memory we must


destroy the objects when they are not required. This task is
performed by destructor.

➢ So the destructor is used to destroy the objects that have been


created by the constructor.

➢ Destructors have the same name as that of the classname, but it


is preceded by a tilde sign.

03/09/2020 OOP 209


Destructors
Syntax:
~classname(arguments)
{
……………;
……………;
}

03/09/2020 OOP 210


Destructors
Characteristics of a destructors

➢ A destructor name must be the same as of its classname, preceded by


tild sign.
➢ It should be declared in public mode.
➢ It does not take any argument.
➢ It does not return any value, not even void.
➢ It is invoked automatically when the objects are destroyed.
➢ It can not be overloaded.
➢ It can not be inherited though it can be called by a derived class.
➢ Destructor can be virtual.
➢ It may not be static.
➢ We can not refer to its addresses.
➢ An object with a destructor can not be used as a member of union.
03/09/2020 OOP 211
Destructors
#include <iostream>

using namespace std;

class TBook
{
public:
TBook();
~TBook();

void message()
{
cout<<"I read the book"<<endl;
}
};

TBook::TBook()
{
cout<<"I see a book"<<endl;
}

TBook::~TBook()
{
cout<<"I close the book"<<endl;
}03/09/2020 OOP 212
int main()
{
cout<<"I am at the library"<<endl;

TBook A;
cout<<"I didn't like that book. I will try another"<<endl;
TBook B;
B.message();
cout<<"I am getting out of the library"<<endl;
return 0;
}

03/09/2020 OOP 213


Output
I am at the library
I see a book
I didn't like that book. I will try another
I see a book
I read the book
I am getting out of the library
I close the book
I close the book

03/09/2020 OOP 214


Static data members
Variables declared with a static keyword are always treated as
static data member
Every static data member has following characteristics
1. It is by default initialize to zero when the first object of its
class is created. No other initialization is permitted.
2. With no. of objects of same class they shares same memory.
3. They retain the previous result without resetting.

Static variables are used to maintain values common to the entire


class.
e.g. A static data member can be used as a counter that records
the occurrences of all the objects.

03/09/2020 OOP 215


Static data members
#include <iostream>

using namespace std;

class item
{
static int count; //initialize to zero/sharable
int number; //initialize to garbage value/non sharable

public:
void get(int a)
{
number=a;
count++;
}

void getcount()
{
cout<<"Count is:"<<count<<endl;
}
};

int item::count; //definition of static data member

03/09/2020 OOP 216


int main()
{
item a,b,c; //count is initialize to zero
a.getcount(); //display count
b.getcount();
c.getcount();

a.get(100); //getting data into object a


b.get(200); //getting data into object b
c.get(300); //getting data into object c

cout<<"After reading data"<<endl;


a.getcount(); //display count
b.getcount();
c.getcount();

return 0;
}

Note: While defining a static variable, some initial value can also be assigned to the variable.
e.g. int item::count=10;

03/09/2020 OOP 217


Output

Count is:0
Count is:0
Count is:0
After reading data
Count is:3
Count is:3
Count is:3

03/09/2020 OOP 218


The static variable count is initialized to zero, when the objects are created. The count
is incremented whenever the data is read into an object. Since the data is read into
objects three times, the variable count is incremented three times. Because there is only
one copy of count shared by all the three objects, all the three output statements cause
the value 3 to be displayed.

03/09/2020 OOP 219


Static Member Functions
➢A function declared with a static keyword is always treated as static
function
➢Every static function in cpp has following features

➢A static function can have access to only other static


members(functions or variables) declared in the same class

➢A static function acts as an global function for a given class.


Therefore such function can be called in the main program by using
scope of class.

➢A static member function can be called using the classname instead


of its objects as follows.
classname::functionname;

03/09/2020 OOP 220


Static Member Functions
#include <iostream>

using namespace std;

class test
{
int code;
static int count; //static member variable

public:
void setcode()
{
code=++count;
}

void showcode()
{
cout<<"Object Number="<<code<<"\n";
}

static void showcount() //static member function


{
cout<<"count="<<count<<"\n";
}
};

int test::count;

03/09/2020 OOP 221


Static Member Functions
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();

test::showcount(); //accessing static function

test t3;
t3.setcode();

test::showcount();

t1.showcode();
t2.showcode();
t3.showcode();

return 0;
}
03/09/2020 OOP 222
Static Member Functions
Output:

count=2
count=3
Object Number=1
Object Number=2
Object Number=3

03/09/2020 OOP 223


Static Member Functions
➢ The static function showcount() displays the number of objects created till that
moment.

➢ A count of number of objects created is maintained by the static variable count.

➢ The function showcode() displays the code number of each object.

➢ code=++count is executed whenever setcode() function is invoked and the


current value of count is assigned to code. Since each object has its own copy
of code, the value contained in the code represents a unique number of its
object.

➢ The following function will not work


static void showcount()
{
cout<<code; //code is not static
}
03/09/2020 OOP 224
Friend Functions
➢ The private data members of a class can not be accessed by any non
member function. The private data members can only be accessed by the
member function of same class.
➢ There are two alternative options to access the private members.
➢ First way is to make the private member as public so that any member
function can access them but this violates the data hiding property of object
oriented programming.
➢ The other mechanism for accessing the private members is called friend
function.
➢ Friend function is a special function which can access the private members
of a class if it (function) is a friend of that class whose it is a friend.
➢ The friend function is not a member function so it may be declared in any
access mode.
➢ The keyword friend informs the compiler that it is not a member function
but it is special function which is a friend of the class

➢ Syntax: friend returntype functionname(parameter);


03/09/2020 OOP 225
Friend Functions
➢ It is similar to the declaration of normal function except that the
function declaration is preceded by the keyword “friend”.
➢ The friend function may either be defined inside the class or outside
the class.
➢ The friend function is not a member function, therefore when it is
defined outside the class, the class name and scope resolution
operator is not used.
➢ When the friend function is defined inside the class, it becomes
inline.
➢ The keyword “friend” can only appear in the function declaration. It
should not be repeated in the function definition.
➢ A friend function, although not a member function, has full access
rights to the private members of the class.
➢ A friend function is responsible to handle objects of same class or of
different classes.
03/09/2020 OOP 226
Friend Functions
Characteristics of friend function
1. It is not in the scope of the class to which it has been declared as
friend.
2. Since it is not in the scope of the class, it can not be called using the
object of that class.
3. It can be invoked like a normal function without the help of any
object.
4. Unlike member functions, it can not access the member names
directly and has to use an object name and dot membership operator
with each member name (e.g. A.x)
5. It can be declared either in the public or the private part of a class
without affecting its meaning.
6. Usually, it has the objects as an arguments.

03/09/2020 OOP 227


Friend Functions
#include <iostream>

using namespace std;

class sample
{
float a,b;

public:
void setvalue()
{
a=25;
b=40;
}
friend int mean(sample s);
};

int mean(sample s)
{
return(s.a+s.b)/2;
}

int main()
{
sample X;
X.setvalue();
cout<<"Mean value is:"<<mean(X)<<endl;
return 0;
}03/09/2020 OOP 228
Friend Functions
#include <iostream>

using namespace std;

class Rectangle
{
private:
int len,wid,area,peri;
public:
void set(int,int);
void cal();
void show();
friend Rectangle add(Rectangle, Rectangle);
};

void Rectangle::set(int l,int w)


{
len=l;
wid=w;
}

void Rectangle::cal()
{
area=len*wid;
peri=2*(len+wid);
}
03/09/2020 OOP 229
void Rectangle::show()
{
cout<<"length="<<len<<endl;
cout<<"Width="<<wid<<endl;
cout<<"Area is="<<area<<endl;
cout<<"Perimeter is="<<peri<<endl;
}

Rectangle add(Rectangle r1, Rectangle r2)


{
Rectangle r3;
r3.len=r1.len+r2.len;
r3.wid=r1.wid+r2.wid;
r3.area=r3.len*r3.wid;
r3.peri=2*(r3.len+r3.wid);
return r3;
}

03/09/2020 OOP 230


int main()
{
Rectangle robj1,robj2,robj3;
robj1.set(10,20);
robj2.set(5,20);

robj1.cal();
robj2.cal();

robj3=add(robj1,robj2);

cout<<"First Rectangle is"<<endl;


robj1.show();

cout<<"Second Rectangle is"<<endl;


robj2.show();

cout<<"Resultant Rectangle is"<<endl;


robj3.show();

return 0;

03/09/2020 OOP 231


Output is:

First Rectangle is
length=10
Width=20
Area is=200
Perimeter
is=60
Second Rectangle is

length=5
Width=20
Area is=100
Perimeter
is=50
Resultant Rectangle is

length=15
Width=40
Area is=600
Perimeter
is=110

03/09/2020 OOP 232


Write a program to add two currency objects
using friend function.
(e.g. 10 rs 60 ps + 20 rs 80 ps)

03/09/2020 OOP 233


Friend Function
Member functions of one class can be friend functions of another class.
In such cases, they are defined using the scope resolution operator as
shown below
class X
{
……….
int fun1();
………..
};
class Y
{
…………
friend int X::fun1(); //fun1 of X is friend of Y
………….
};
03/09/2020 OOP 234
Friend Function
We can also declare all the member functions of one class as the friend
of another class. In this case, the class is called a friend class.

class Z
{
friend class X; //all member functions of X are friends to Z
};

03/09/2020 OOP 235


#include <iostream>
Friend Function
using namespace std;

class ABC;

class XYZ
{
int x;

public:
void set(int i)
{
x=i;
}
friend void max(XYZ, ABC);
};

class ABC
{
int a;

public:
void set(int i)
{
a=i;
}
friend void max(XYZ, ABC);
};
03/09/2020 OOP 236
void max(XYZ m, ABC n)
{
if(m.x>=n.a)
cout<<m.x;
else
cout<<n.a;
}

int main()
{
ABC p;
p.set(10);

XYZ q;
q.set(20);

max(q,p);
return 0;
}

03/09/2020 OOP 237


Continued…
Note: The function max() has arguments from
both XYZ and ABC. When the function max() is
declared as a friend in XYZ for the first time, the
compiler will not acknowledge the presence of
ABC unless its name is declared in the beginning
as
class ABC;
This is known as ‘forward’ declaration.

03/09/2020 OOP 238


Continued…
Write any program for addition of two objects
from two different classes.

03/09/2020 OOP 239


Friend Class
This allows the friend class to access the private
data members of the another class.

03/09/2020 OOP 240


#include <iostream>
Friend Class
using namespace std;

class A
{
private:
int data;
friend class B;
public:
A()
{
data=5;
}
};

class B
{
public:
int sub(int x)
{
A obj1;
return obj1.data-x;
}
};
03/09/2020 OOP 241
Continued…
int main()
{
B obj2;
cout<<"Result is="<<obj2.sub(2);
return 0;
}

03/09/2020 OOP 242


Inline Functions
What is inline function?
Inline functions are functions where the call is made to inline functions. The
actual code then gets placed in the calling program.

Reason for the need of inline function:


Normally, a function call transfers the control from the calling program to the
function and after the execution of the program returns the control back to the
calling program after the function call.
main()
{
……………..
display(); // calling program
……………..
}

void display()
{
…………….. // called program
}
03/09/2020 OOP 243
Inline Functions
Advantage of using this concept: Save the program space and memory space
because the function is stored only in one place and is only executed when it is
called.

Disadvantages: This execution may be time consuming since the registers and
other processes must be saved before the function gets called.

We can save the time of execution by using inline functions.

03/09/2020 OOP 244


Inline Functions
What happens when an inline functions is written?
➢ The inline function takes the format as a normal function but when it is
compiled it is compiled as inline code.
➢ The function is placed separately as inline function, thus adding readability
to the source program.
➢ When the program is compiled, the code present in the function body is
replaced in the place of function call.

03/09/2020 OOP 245


Inline Functions

03/09/2020 OOP 246


Inline Functions
Syntax:
inline returntype function_name(arguments)

Situations where inline expansion may not work are:


➢ If the function is large.
➢ For functions returning values, if a loop, a switch or a goto exist.
➢ For functions not returning values, is a return statement exists.
➢ If function contains static variables.
➢ If inline functions are recursive.

03/09/2020 OOP 247


Inline Functions
#include <iostream>
using namespace std;

int test(int);

int main()
{
int x;
cout<<"Enter the values:"<<endl;
cin>>x;
cout<<"The output is:"<<test(x);
return 0;
}

inline int test(int x1)


{
return 5*x1;
}

03/09/2020 OOP 248


Inline Functions
Output:

Enter the values:

10

The output is:50

03/09/2020 OOP 249


Inline Member Function
Inline member function
Inline function can be member functions of a class. The
properties of inline function which are described above remain
true though we define inline function inside the class.
class student
{
int marks, rollno;
public:
inline void getdata(int m, int n)
{
marks=m;
rollno=r;
}
03/09/2020 OOP 250
};
Program for Practice
1. Write a C++ program create a calculator for an arithmetic operator (+, -, *, /).
The program should take two operands from user and performs the operation on
those two operands depending upon the operator entered by user. Use a switch
statement to select the operation. Finally, display the result.
Some sample interaction with the program might look like this:
Enter first number, operator, second number: 10 / 3
Answer = 3.333333
Do another (y/n)? y
Enter first number, operator, second number: 12 + 100
Answer = 112
Do another (y/n)? n

03/09/2020 OOP 251


Program for Practice
2. A book shop maintains the inventory of books that are being sold at the shop.
The list includes details such as author, title, price, publisher and stock position.
Whenever a customer wants a book, the sales person inputs the title and author
and the system searches the list and displays whether it is available or not. If it is
not, an appropriate message is displayed. If it is, then the system displays the
book details and requests for the number of copies required. If the requested
copies book details and requests for the number of copies required. If the
requested copies are available, the total cost of the requested copies is displayed;
otherwise the message ―Required copies not in stock‖ is displayed. Design a
system using a class called books with suitable member functions and
Constructors. Use new operator in constructors to allocate memory space
required. Implement C++ program for the system.

03/09/2020 OOP 252


Program for Practice
3. Implement a class CppArray which is identical to a one-dimensional C++ array
(i.e., the index set is a set of consecutive integers starting at 0) except for the
following :
1. It performs range checking.
2. It allows one to be assigned to another array through the use of the assignment
operator (e.g. cp1= cp2)
3. It supports a function that returns the size of the array.
4. It allows the reading or printing of array through the use of cout and cin.

03/09/2020 OOP 253


END OF FIRST UNIT

THANK YOU

03/09/2020 OOP 254

You might also like