Units 2
Units 2
5
OBJECT ORIENTED PROGRAMMING
POP does not have any access OOP has access specifiers named
specifier. Public, Private, Protected, etc.
In POP, data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other
through member functions.
To add new data and function in OOP provides an easy way to add
POP is not so easy. new data and function.
In POP, most function uses global In OOP, data cannot move easily
data for sharing that can be accessed from function to function, it can be
freely from function to function in kept public or private so we can
the system. control the access of data.
POP does not have any proper way OOP provides data hiding so
for hiding data so it is less secure. provides more security.
In POP, overloading is not possible. In OOP, overloading is possible in
the form of Function Overloading
and Operator Overloading.
Example of POP are: C, VB, FOR- Example of OOP are: C++, JAVA,
TRAN, Pascal. VB.NET, C#.NET.
6
Chapter 1 : Objects Methodology
7
OBJECT ORIENTED PROGRAMMING
8
Chapter 1 : Objects Methodology
1.7 Questions
Q1. Why does hardware not provide flexibility of operations to the user ?
Q2. How is a program related to software?
Q3. What is the signature of a method?
Q4. Differentiate between information hiding and encapsulation.
Q5. What is the difference between object-oriented and object-based programming
languages?
Q6. What is the need of Object Oriented Programming ?
Q7. Differentiate Procedure Oriented Programming & Object Oriented
Programming
Q8. List and explain benefits of OOP .
Q9. List and explain application of OOPS
PRINCIPLES OF OOPS
2.0 Object Oriented Programming Paradigm
11
OBJECT ORIENTED PROGRAMMING
2.1.0 Class
A group of objects that share common properties for data part and some
program part are collectively called as class.
In C ++ a class is a new data type that contains member variables and member
functions that operate on the variables.
The most remarkable feature of C + + is a class. The class binds together
data and methods which work on data. The class is an abstract data type
(ADI) so creation of class simply creates a template.
The class is a keyword.
The general syntax of creating a class in C++ is given below:
12
Chapter 2 : Principles of OOPS
Following this keyword class, class_name represents name of the class. The class
name must obey rules of writing identifier as class_name is nothing but an identifier.
The class is opened by opening brace} and closed by closing brace}. The class
definition/declaration must end with semicolon. Inside the class we define the data
members and member functions. They may be defined either public, private or jn
protected mode.
There are three different types of mode :
1. public
2. private
3. protected.
2.1.1 Object
Objects are the basic run time entities in an Object Oriented System.
They may represent a person, a bank account, a table of data or any item
that the program has to handle.
They may also represent user-defined data such as vector, time, and lists.
When a program is executed, the objects interact by sending messages to
one another.
Creating objects is similar to declaring variables.
Syntax:
<Class Name> <Object Name>;
For Example:
Student s1;
Where Student is a class name and s1 is its object.
13
OBJECT ORIENTED PROGRAMMING
2.1.2 Polymorphism
Poly means many. Morphism means forms.
Polymorphism feature enables classes to provide different implementation
of methods having the same name.
There are two types of polymorphism:
1. Compile time (Overloading)
2. Run time (Overriding)
2.1.3 Inheritance
Inheritance is the process by which objects of one class acquire the properties
of objects of another class.
It supports the concept of hierarchical classification.
The existing class is called as base class and a new class which is created on
the basis of base class is called as derived class.
There are 5 different types of inheritance, i.e.:
Single level
Multilevel
Multiple
Hierarchical
Hybrid
2.1.4 Reusability
The concept of inheritance provides an important feature to the object-oriented
languagereusability.
A programmer can take an existing class and, without modifying it, and
additional features and capabilities to it.
This is done by deriving a new class from an existing class.
14
Chapter 2 : Principles of OOPS
C++ provides the ability to define classes and functions as its primary
encapsulation mechanisms.
Message passing here means object calling the method and passing
parameters.
Message passing is nothing but the calling the method of the class and sending
parameters.
The method is turn executes in response to a message.
OBJECT ORIENTED PROGRAMMING
2.2 Summary
The programs are the means through which we can make the computers
produce the useful desired outputs.
Out of a variety of programming paradigms being used by practitioners as
well as the researchers, the structured and the object-oriented programming
paradigm and corresponding structured and object-oriented programming
have been in focus for quite some time now.
In this unit, you studied that the structured programming languages initially
helped in coping with the inherent complexity of the softwares of those times
but later on, were found wanting in the handing the same as far as the software
of present days are concerned.
you were introduced to the concepts of object-oriented programming
paradigm and it was illustrated as to how this paradigm is closer to natural
human thinking.
It was followed by the illustrations of some more concepts of object-oriented
programming like classes, objects, message passing, interface, associations,
inheritance and polymorphism.
In the end, you saw what the various benefits of OOPs are and how can these
help in producing good quality software.
CLASSES AND OBJECTS
A class is defined in C++ using keyword class followed by the name of class. The
body of class is defined inside the curly brackets and terminated by a semicolon at
the end.
OBJECT ORIENTED PROGRAMMING
Declaring Objects
When a class is defined, only the specification for the object is defined; no memory
or storage is allocated. To use the data and access functions defined in the class, you
need to create objects.
Syntax:
ClassName ObjectName;
The data members and member functions of class can be accessed using the dot(‘.’)
operator with the object. For example if the name of object is obj and you want to
access the member function with the name printName() then you will have to
write obj.printName() .
The public data members are also accessed in the same way given however the
private data members are not allowed to be accessed directly by the object. Accessing
a data member depends solely on the access control of that data member.
This access control is given by Access modifiers in C++. There are three access
modifiers : public, private and protected.
Class A
{
private:
int x;
void fun1()
{
// This function can refer to data members x, y, z and functions fun1(), fun2()
and fun3()
40
Chapter 3 : Classes and Objects
}
protected:
int y;
void fun2()
{
//This function can also refer to data members x, y, z and functions fun1(),
fun2() and fun3()
}
public :
int z;
void fun3()
{
//This function can also refer to data members x, y, z and functions fun1(),
fun2() and fun3()
}
};
Now, consider the statements
A obja; //obja is an object of class A
int b; // b is an integer variable
The above statements define an object obja and an integer variable b. The accessibility of
members of the class A is illustrated through the obja as follows:
1. Accessing private members of the class A:
b=obja.x; //Won t Work: object can not access private data member „x obja.fun1();
//Won t Work: object can not access private member function fun1() Both the statements
are illegal because the private members of the class are notaccessible.
41
OPERATORS IN C++ :
C++ has a rich set of operators. All C operators are valid in C++ also. In addition. C++
introduces some new operators.
Like C,C++ is also a block-structured language. Block -structured language. Blocks and
scopes can be used in constructing programs. We know same variables can be declared in different
blocks because the variables declared in blocks are local to that function.
Blocks in C++ are often nested.
Example:
{
Int x =10;
}
Block2 contained in block l .Note that declaration in an inner block hides a declaration of the
same variable in an outer block and therefore each declaration of x causes it to refer to a different data object .
With in the inner block the variable x will refer to the data object declared there in.
In C,the global version of a variable can't be accessed from with in the inner block.
C++ resolves this problem by introducing a new operator :: called the scope resolution operator .This can be
used to uncover a hidden variable.
Example:
#include <iostrcam.h>
int m=10;
main()
{
int m=20;
{
int k=m;
int m=30;
cout<<”we are in inner block”;
cout<<"k="<<k<<endl;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
cout<<”\n we are in outer block \n”;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
C++ also support those functions it also defines two unary operators new and delete that
perform the task of allocating and freeing the memory in a better and easier way.
The new operator can be used to create objects of any type. Syntax: pointer-
Example:
p=new int; q=new int;
float *p=newfloat;
*p=25;
*q=7.5;
Assign 25 to the newly created int object and 7.5 to the float object.We can also initialize the memory
using the new operator.
Syntax:
int *p=ne\v int(25);
float *q =new float(7.5);
new can be used to create a memory space for any data type including user defined such as
arrays,structures,and classes .The general form for a one-dimensional array is:
If a data object is no longer needed, it is destroyed to release the memory space for reuse.
Example:
delete p;
delete q;
If we want to free a dynamically allocated array ,we must use the following
form of delete.
MANIPULATERS:
Manipulators are operator that are used to format the data display. The most commonly manipulators are
endl and setw.
The endl manipulator, when used in an output statement, causes a line feed to be insert.(just like \n)
Example:
cout<<”m=”<<m<<endl;
cout<<”n=”<<n<<endl;
cout<<”p=”<<p<<endl;
If we assume the values of the variables as 2597,14 and 175 respectively
m=2597; n=14;
p=175
It was want to print all nos in right justified way use setw which specify a common field width
for all the nos.
Example: cout<<setw(5)<<sum<<endl;
cout<<setw(10)<<”basic”<<setw(10<<basic<<endl;
Cout<<setw(10)<<”allowance”<<setw(10<<allowance<<endl;
cout<<setw(10)<<”total=”<<setw(10)<<total;
Member Functions in Classes
A member function performs an operation required by the class. It is the actual interface to initiate an
action of an object belonging to a class. It may be used to read, manipulate, or display the data member.
The data member of a class must be declared within the body of the class, while the member functions of a
class can bedefined in two places:
⬧ Inside class definition
⬧ Outside class definition
The syntax of a member function definition changes depending on whether it is defined inside or outside
the class declaration/definition. However, irrespective of the location of their definition, the member
function must perform the same operation. Thus, the code inside the function body would be identical in
both the cases. The compiler treats these two definitions in a different manner. Let us see, how we can
define the member function inside the class definition.
The syntax for specifying a member function declaration is similar to a normal function definition except
that is enclosed within the body of a class. For example, we could define the class as follows:
class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration
void minimum(void) //definition
{
int min;
min=x;
if (min>y)
min=y;
if (min>z)
min=z;
cout<<“\n Minimum value is =”<<min<<endl;
}
};
if you look at the above declaration of class number you can observe that the member function get_data() and
maiximun() are declared, but they are not defined. The only member function which is defined in the class
body is minimum(). When a function is defined inside a class, it is treated as a inline function. Thus,
member function minimum is a inline function. Generally, only small functions are defined inside theclass.
Now let us see how we can define the function outside the class body. Member functions
that are declared inside a class have to be defined outside the class. Their definition is very
much like the normal function. Can you tell how does a compiler know to which class
outside defined function belong? Yes, there should be a mechanism of binding the functions
to the class to which they belong. This is done by the scope resolution operator (::). It acts as
an identity-label. This label tells the compiler which class the function belongs to. The
common syntax for member function definition outside the class is as follows:
}
void Number :: maximum(void)
{
int max;
max=x;
if (max<y)
max=y;
if (max<z)
max=z;
cout<<“\n Maximun value is =”<<max<<endl;
}
if you look at the above declaration of class Number, you can easily see that the member function
get_data() and maiximun() are declared in the class. Thus, it is necessary that you have to define this
function. You can also observe in the above snapshot of C++ program identity label (::) which are used in
void Number :: get_data(void) and void Number ::maximum(void) tell the compiler the
functionget_data() and maximum() belong to the class Number
let us see the complete C++ program to find out the minimum and maximum of three given integer
numbers
#include<iostream.h>
class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration
void minimum(void) //definition
{
int min;
min=x;
if (min>y)
min=y;
if (min>z)
min=z;
cout<<“\n Minimum value is =”<<min<<endl;
}
};
void Number :: get_data(void)
{
cout<< “\n Enter the value of fist number(x):”<<endl;
cin>>x;
cout<< “\n Enter the value of second number(y):”<<endl;
cin>>y;
cout<< “\n Enter the value of third number(z):”<<endl;
cin>>z;
}
void Number :: maximum(void)
{
int max;
max=x;
if (max<y)
max=y;
if (max<z)
max=z;
cout<<“\n Maximun value is =”<<max<<endl;
}
void main()
{
Number num;
num.get_data();
num.minimum();
num.maximum();
}
output:
Enter the value of the first number (x):
10
Enter the value of the second number (y):
20
Enter the value of the third number (z):
5
Minimum value is=5
Maximum value is=20
CONSTRUCTORS AND DESTRUCTORS
Constructor is a special member function whose name is same as the name of its class in which it is
declared and defined. The purpose of the constructor is to initialize the objects of the class. The constructor
is called so because it is used to construct the objects of the class.
Example of constructor and later illustrate its various features :
OUTPUT :
1. The constructors are always declared in the public section. If declared in the private
section then objects are can only be created inside the member functions but serve no
purpose.
2. They are invoked automatically when objects of the class are created. The
declaration demo d;creates an object d which automatically calls the constructor of
the class and prints Hello from constructor.
3. They do not have any return type not even void so they cannot return any value.
4. Constructors cannot be inherited, but they can be called from the constructorsof derived
class.
5. Constructors are used to construct the object of the class.
6. The constructor with no argument is known as default constructor of theclass. The
default constructor for the class demo will be demo : demo( )
7. Constructors which take arguments like a function takes are known as
parameterized constructor.
8. There is no limit of the number of constructors declared in a class but theyall must
conform to rules of function overloading.
9. Constructor can have default arguments.
10. Addresses of constructors cannot be taken.
11. Constructors cannot be virtual.
12. Constructor make implicit calls to operators new and delete in case memoryallocation and de-
allocation is to be performed
TYPES OF CONSTRUCTURS
i) Default Constructors
#include<iostream.h>
#include<conio.h>
class abc
{
private:
char nm[];
public:
abc ( )
{
cout<<”enter your name:”;
cin>>nm;
}
void display( )
{
cout<<nm;
}
};
int main( )
{
clrscr( );
abc d;
d.display( );
getch( );
return(0);
}
};
integer:: integer (int x, int y) m=x;n=y;
{
}
the argument can be passed to the constructor by calling the constructor
implicitly.
integer int 1 = integer(0,100); // explicit call
integer int 1(0,100); //implicite call
CLASS WITH CONSTRUCTOR:-
#include<iostream.h>
class integer
{
int m,n;
public:
integer(int,int);
void display(void)
{
cout<<”m=:”<<m ;
cout<<”n=”<<n;
}
};
integer :: integer( int x,int y) // constructor defined
{
m=x;
n=y;
}
int main( )
{
output:
object 1m=0 n=100
object2 m=25 n=75
output :-
id of A:100
id of B:100
id of C:100
id of D:100
int length;
public:
string ( )
{
length=0;
name= new char [length+1]; /* one extra for \0 */
}
string( char *s) //constructor 2
{
length=strlen(s);
name=new char [length+1];
strcpy(name,s);
}
void display(void)
{
cout<<name<<endl;
}
void join(string &a .string &b)
{
length=a. length +b . length;
delete name;
name=new char[length+l]; /* dynamic allocation */
strcpy(name,a.name);
strcat(name,b.name);
}
};
int main( )
{
char * first = “Joseph” ;
string name1(first),name2(“louis”),naine3( “LaGrange”),sl,s2;
sl.join(name1,name2);
s2.join(s1,name3);
namel.display( );
name2.display( );
name3.display( );
s1.display( );
s2.display( );
}
output :-
Joseph
Louis
language
Joseph Louis
Joseph Louis Language
4.1 Destructor
A destructor is a member function of the class whose name is same as the name of the class
but the preceded with tilde sign (~). The purpose of destructor is to destroy the object when it is
no longer needed or goes out of scope. As a very small exampleof destructor see the program
given below :
#include <iostream.h>
#include <conio.h>
class demo
{
public :
demo( )
{
cout<<“Constructor called\n”;
}
~demo( )
{
cout<<“Destructor called”<<endl;
}
};
void main( )
{
clrscr( );
demo d;
getch( );
}
OUTPUT :
Constructor called
Destructor called
FRIENDLY FUNCTIONS:-
We know private members can not be accessed from outside the class. That is a non -
member function can't have an access to the private data of a class. However there could be a case
where two classes manager and scientist, have been defined we should like to use a function income-
tax to operate on the objects of both these classes.
In such situations, c++ allows the common function lo be made friendly with both the classes , there
by following the function to have access to the private data of these classes .Such a function need not
be a member of any of these classes.
To make an outside function "friendly" to a class, we have to simply declare this function as a friend
of the classes as shown below :
class ABC
{
public:
The function declaration should be preceded by the keyword friend , The function is defined else
where in the program like a normal C ++ function . The function definition does not use their the
keyword friend or the scope operator :: . The functions that are declared with the keyword friend are
known as friend functions. A function can be declared as a friend in any no of classes. A friend
function, as though not a member function , has full access rights to the private members of the class.
Example:
#include<iostream.h>
class sample
{
int a;
int b;
public:
void setvalue( ) { a=25;b=40;}
friend float mean( sample s);
}
float mean (sample s)
{
return (float(s.a+s.b)/2.0);
}
int main ( )
{
sample x;
x . setvalue( );
cout<<”mean value=”<<mean(x)<<endl;
return(0);
output:
mean value : 32.5
this Pointer
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a
class. Only member functions have a this pointer.
Let us try the following example to understand the concept of this pointer “
#include <iostream>
class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<“Constructor called.” << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(5.6, 1.2, 5.1); // Declare box1
Box Box2(2.5, 4.1, 6.1); // Declare box2
if(Box1.compare(Box2)) {
cout << “Box2 is smaller than Box1” <<endl;
} else {
cout << “Box2 is equal to or larger than Box1” <<endl;
}
return 0;
}
Output :
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1