Object Oriented Programming (210243) SE Computer Engineering
Object Oriented Programming (210243) SE Computer Engineering
Object Oriented Programming (210243) SE Computer Engineering
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
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
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
03/09/2020 OOP 8
OOP Paradigms
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();
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
};
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
03/09/2020 OOP 31
C++ As OOP Language
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
03/09/2020 OOP 35
Continued…
#include<iostream>: This directive causes the
pre-processor to add the contents of the iostream
file
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
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.
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
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;
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…
03/09/2020 OOP 48
Continued….
Control
Structures
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.
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…
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…
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…
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…
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…
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";
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";
03/09/2020 OOP 90
Keywords
The keywords are the special symbols.
03/09/2020 OOP 91
Continued…
A list of 32 Keywords in C++ Language which are
also available in C language are given below.
03/09/2020 OOP 92
Continued…
A list of 30 Keywords in C++ Language which are
not available in C language are given below.
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.
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.
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.
30 -decimal integer
40.12 – floating point number
037 – Octal integer
0X2 – hexadecimal integer
“MET” - string constant
‘A’ – character constant
Types of Operators:
1. Arithmetic Operators
+, -, *, /, % are the binary 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
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.
struct student
{
char name[20];
int roll_no;
float total_marks;
};
#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:
#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.
5 10 0
0 15 20
30 0 10
2 5 5
4 0 3
9 1 8
Address Value
Pointer Variable
DeDE
Symbol Name Description
Declaring a pointer
➢ 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.
In C++, a variable can be initialized at run time using expressions at the place
of declaration.
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.
Note: Here & is not an address operator. The notation float & means
reference to float.
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
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;
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
The statements
*p=25; *q=7.5;
Assigns 25 to the newly created int object and 7.5 to the float object
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;
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.
delete [] pointer_variable;
e.g. delete[] p;
Will delete the entire array pointed by p.
In ‘C’;
Syntax:
(datatypename)expression
e.g. average=sum/(float)i;
In ‘C++’
Syntax:
datatypename(expression)
e.g. average=sum/float(i)
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.
User Defined
Library Function Function
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.
Syntax:
datatype function_name(argument list);
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.
A C++ function can also have an ‘open’ parameter list by the use of
ellipses in the prototype as shown below:
void abc(…);
The variables x &y are passed to the called function test where it
is associated with variables s and u.
e.g. value=price(5000,7,0.12);
Passes an explicit value of 0.12 to r.
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
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
#include <iostream>
using namespace std;
class math
{
private: int no1,no2;
public:
void setdata(int,int);
void showdata();
int product();
int addition();
int substraction();
};
int math::product()
{
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.
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;
}
int main()
{
employee e[5];
for(int i=0;i<5;i++)
{
e[i].get();
}
for(int i=0;i<5;i++)
{
e[i].show();
}
return 0;
}
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;
}
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();
}
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.
class bank
{
int p,q;
public:
bank();
};
bank::bank()
{
p=500;
q=700;
}
int main()
{
bank b1,b2;
return 0;
}
Syntax:
classname( )
{
……………;
……………;
}
Syntax:
classname( argument list)
{
……………;
……………;
}
Syntax:
classname( classname &object)
{
……………;
……………;
}
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;
}
void Rectangle::cal()
{
area=length*width;
peri=2*(length+width);
}
Rectangle r2;
cout<<"Second Rectangle is:"<<endl;
r2.cal();
r2.show();
Rectangle r3(r1);
// Rectangle r3=r1;
Length is=2
Width is=3
Area is=6
Perimeter is=10
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;
}
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;
}
};
return 0;
}
Note: While defining a static variable, some initial value can also be assigned to the variable.
e.g. int item::count=10;
Count is:0
Count is:0
Count is:0
After reading data
Count is:3
Count is:3
Count is:3
class test
{
int code;
static int count; //static member variable
public:
void setcode()
{
code=++count;
}
void showcode()
{
cout<<"Object Number="<<code<<"\n";
}
int test::count;
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
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>
class Rectangle
{
private:
int len,wid,area,peri;
public:
void set(int,int);
void cal();
void show();
friend Rectangle add(Rectangle, Rectangle);
};
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;
}
robj1.cal();
robj2.cal();
robj3=add(robj1,robj2);
return 0;
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
class Z
{
friend class X; //all member functions of X are friends to Z
};
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;
}
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;
}
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.
int test(int);
int main()
{
int x;
cout<<"Enter the values:"<<endl;
cin>>x;
cout<<"The output is:"<<test(x);
return 0;
}
10
THANK YOU