0% found this document useful (0 votes)
57 views12 pages

Oop Concepts N

Uploaded by

ankushshastry
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views12 pages

Oop Concepts N

Uploaded by

ankushshastry
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

OOP CONCEPTS

Difference between Object Oriented Programming and Procedure Oriented Programming


Object Oriented Programming (OOP) Procedure Oriented Programming (POP)
1. Emphasis is on Data 1. Emphasis is on doing things (Algorithms,
Program code, Procedures or Functions)
2. Program is written as a collection of objects 2. Program is written using logical steps
3. Data is secured (Prevents accidental change 3. Chances of accidental change in data is
of data, since data is not allowed to be more (Since, data moves from function to
accessed from external function) function; because of Global variables used)
4. Features like data encapsulation, 4. No such features are supported
polymorphism, inheritance are supported.
5. Follows Bottom up approach in program 5. Follows top down approach
design
6. Supports high level of Code Reusability. 6. Less support for code reusability.
7. Easy to extend (Creation of New objects 7. Not so easy to extend & maintain software
is easy) & maintain. developed using POP concept.
Note: Some earlier programming Languages like C, Pascal, COBOL, etc. are Procedure oriented
programming (POP) Languages. Whereas, C++, Java, Python, Ada, Small talk, VC++, etc. are
OOP languages.

Characteristics of OOP:
Some of the important features of object oriented programming are namely:
 Objects
 Classes
 Data Encapsulation
 Polymorphism
 Inheritance
 Data Abstraction
 Reusability
 Modularity
 Message passing

Object:
Object is the basic unit of object-oriented programming.
An object represents a particular instance of a class. An object is collection of data members
and member functions. Every object must belong to a particular class.

Class:
A class is the blue print of an object. Once a class is defined, any number of objects of that class
can be created.

A class is a user defined data type which contains data members and member functions.

Data encapsulation
Data encapsulation combines both data and functions into a single unit called class. The data is
allowed to be accessed only through the functions. Data encapsulation prevents direct access to
data i.e., the data is hidden from the users. The prevention of direct access of data by the users is
called as data hiding. Data hiding help in securing the data (data security).

Polymorphism
(Poly means many, morph means form). Polymorphism means “many forms”. It is the ability of
processing data in more than one form. In C++, Polymorphism is implemented through Function
Overloading, and Operator overloading.
It is a concept where the same operation does different things in different situations. i.e., The same
operation behaves differently in different instances. For example, an addition operator is used to
add 2 numbers. The same operator can be used to concatenate two strings, to add 2 complex
numbers, to add 2 arrays, etc. This type of polymorphism is called as operator overloading.
In function polymorphism, the same function name can be used to do different operations,
depending on the number of arguments and type of arguments. The function polymorphism is also
called function overloading.
Polymorphism is implemented using
(i) function overloading and
(ii) operator overloading concepts

Inheritance
Inheritance is the process of creating a new class from an existing class or base class. The base
class is also known as parent class or super class. Derived class is also known as a child class or
sub class. Inheritance is the process by which an object of a derived class acquires the properties
of base class. Thus object of one class (derived class) inherits the properties of another class (base
class) through inheritance.
For example, a class two Wheeler (derived class) is derived from the class Automobile (Base
class). Now, the derived class in addition to its own properties can acquire the properties of the
base class.
Inheritance helps in code reusability.

Reusability
Once a Base class is defined, tested and ready to use, it can be distributed to other programmers to
use in their own programs. This is called as reusability. Using the concept of inheritance, other
programmers can use the existing class, add new features or modify the existing code by deriving
a new class from the existing class. It is similar to use library functions in different programs. So,
the concept of reusability saves the programmer time and effort.

Data Abstraction:
It refers to the act of representing essential features without including the background details
Example : For driving , accelerator, clutch and brake controls need to be learnt rather than knowing
the working of engine and other details.

Modularity :
The act of partitioning a complex problem into simpler fragments called modules is called as
modularity. It reduces the complexity of a program / software. It helps in developing the programs
(or modules) in parallel; hence, reduces the program development time.

Message passing
In OOP, message passing is invoking (or calling) a member function. It involves specifying the
name of an object, name of the member function and the arguments to be passed if any.
For example, consider the message: addition.findtotal(a, b);
Here, addition is the object, and findtotal() is the function and a, b are the arguments to be passed.

Advantages of OOP
 Provides data security. Due to data encapsulation, only the functions within the class
are allowed to access the data. External functions are not allowed to access or
modify the data.
 Used to develop complex softwares.
 Code reusability helps in reducing the Complexity of program development.
 Concept of reusability achieved by inheritance saves the programmer time and effort.
 Easy to extend by adding specific features to each derived class as needed.
 Software developed using OOP concept results in greater reliability.
 Programs developed using OOP are easier to make changes and easy to maintain.
 The software can be modularized or partitioned based on classes & objects.
Creation and implementation of OOP code is easy and reduces software development time.
 The concept of data abstraction separates object specification and object implementation.
 Since objects communicate through message passing, this makes the interfacing with
outside system very simple.

Limitations of OOP
o Conversion of real world problem into object oriented model is difficult for some systems.
o Some developers may find it difficult initially to get used to OOP concepts.

Applications of OOP
 User interface design such as windows
 Computer graphics applications
 Object-oriented database
 Simulation and modeling
 Real time systems
 Artificial intelligence and expert systems
 CAD/CAM software
CLASSES and OBJECTS
Classes and Objects are the major components of Object Oriented Programming. A class defines
the nature of an object. For each object we need to define a class. Defining a class is like describing
an object.

Objects are the entities of the real world. For example, what we see around us: the book you are
reading, the pen you are holding, the desk you are sitting, college, computer, bike and so on, all
are considered as objects. All these objects have state (or attributes) and behaviours (functions).
For example, the class pen has some attributes like manufacturer, ink color, price, etc.; and
behaviour like writing (how to write using pen), how ink flows, etc.

Defining a class is like preparing a blueprint of your house. Having blue print of a house, does
it mean the house is built or exist? No, isn’t it? A house built using the blue print is an object. The
house built, i.e., an object is an instance of the class. Remember, once you have a blueprint you
can build as many houses as you can. The same way, once we define a class, we can create many
objects of that class as we need. A Class can create a group of similar objects.

A class is often referred to as blueprint of an object. It describes the object. A class describes
mainly 2 things:
(i) attributes: which tells what the object “consists of”,
(ii) behaviors: which tells what the object “does”
For example, a bike class has attributes like engine, gear box, etc. and behaviors like what the
engine should do, how the gear box should work, what are all happen while riding the bike / how
to ride the bike, etc.
The same way, in C++, a class consists of attributes called data members and behaviors called
member functions.

Defining a class
The syntax of a class definition: Example of a class definition
class className class addition
{ {
access specifier: private: // access specifier
data members; int a,b; // data members
access specifier: public:
member functions(); void total() //member function
};  Semicolon required {
cin>>a>>b; //data members accessed directly
// in member functions
cout<<”Sum=”<<a+b;
}
};
where
 A class definition starts with the keyword class followed by the className.
(Note: className : is the name of the class and can be treated as the user defined data type.
Using this name we can create objects of type className.)
 body of a class is enclosed by a pair of curly braces.
 The semicolon(;) at the end of class definition is mandatory. (Note: A class definition may
end with a list of object declarations, followed by ; .)

The data members are the variables declared inside the class. member functions are the functions
declared or defined inside the class. The member functions can access the data members of the
class directly.

Access specifiers (or access modifier) in a Class:


Access specifiers are used to identify access rights for the data members and member functions of
the class.
Access specifier determines the scope of data members & member functions in a program.
There are three types of access specifiers in C++:
 private
 protected
 public

Member-Access Control
1) The private members of a class can be accessed only by the member functions of that class;
i.e., Private members cannot be accessed outside the class. (or Class members declared as
private can be accessed only by member functions of that class and friends of the class).
2) The protected members are similar to private members of a class if a single class exists. But,
if a class is derived from an already existing class (i.e., base class), the protected members of
the base class are accessible in the derived class also. (or Class members declared as protected
can be accessed by member functions and friends of the class. Additionally, they can be
accessed by derived class of that base class).
3). The public members can be accessed by any function outside the class also.

Importance of Access Specifiers
It helps in implementing data hiding and data abstraction. Access control helps to us to access
members of a class in proper way.

Note: Class defines types of data structures and the functions that operate on those data structures.
A Class binds data and its associated functions under one unit. It is called encapsulation. The
body of a class can contain optional list of data members (variables) & member function(s), and
access specifiers. The default access specifier is private; i.e., if access specifier is not mentioned,
the member is private by default.

OBJECTS in C++:
Objects represent instances of a class. Objects are basic run time entities in an object oriented
system.
Creating object / defining the object of a class:
The general syntax of defining or declaring an object of a class is:-
className objectName;

In C++, a class variable is known as an object. The declaration of an object is similar to that of
declaring a variable of any data type (like int n).
Area circle,square; // Declare objects circle, square of class Area
Area rectangle; // Create object rectangle of class type Area

Each of the objects circle, square, rectangle will have their own copy of data
members.
An object can be declared in the class definition also as shown below:
class Area
{
…. // Body of a class or definition of a class
} circle,square;

Accessing / calling members of a class


The member functions of a class can access data members whether they are declared as private or
public. Public member of a class can be accessed through an object of the class. But, private
members of a class cannot be accessed through an object (as told earlier, only the member
functions of the class can access private members). They are accessed or referred or called using
object of that class with the help of dot operator (.).
The general syntax for accessing data member of a class is:-
objectName.dataMember;

The general syntax for accessing member function of a class is:-


objectNname.memberFunctionname([actual arguments if any]);

The dot ('.') used above is called the dot operator or class member access operator. The dot
operator is used to connect the object and the member. The private data of a class can be accessed
only through the member function of that class.
Note:
 Definition of a class will not reserve memory for any data members and member functions.
 Only when an Object of a class is created/defined, Memory is reserved.
 Separate memory is reserved for data members of each object whereas a single copy of member
functions is shared by various objects.
 The data members of a class should not be initialized when they are declared. For example,
class Data
{
private:
int a = 10; // Compilation Error: Invalid initialization of member
public:
int b = 20; // Compilation Error: Invalid initialization of data member
……
};

Defining the member functions (Class methods definition)


Member functions can be defined in two places:-
1) Defining member function outside the class definition

The member functions of a class can be defined outside the class definition. It is only declared
inside the class but defined outside the class. The general syntax for defining member function
outside the class definition is:
returntype ClassName::functionName(argument list if any)
{
….. // Body of the member function
}
Where symbol :: is a scope resolution operator.
The scope resolution operator (::) specifies the class to which the member being declared
belongs to. It is mainly used to define the member function outside the class.
class Array
{
int a[10],i;
public:
void readArray(); // Member Function declared inside class

};
void Array::readArray() // Member Function defined outside the class
{
for (i=0;i<5;i++)
cin>>a[i];
}
We generally define a member function outside a class, whenever the function contains complex
statements like loop, switch, function call statements, etc.

2) Inside the class definition


The member function of a class can be declared and defined inside the class definition.
class sum
{
int a, b, total;
public:
void getdata() //member function defined inside class
{ cout< ”\n Enter the value of A and B”;
cin>>a>>b;
}
};
We generally define a member function inside a class, if the function is small and has simple
statements. When member functions are defined inside the class definition, the member functions
become inline functions by default.

Program to demonstrate the Importance of Access specifiers:


class Addition
{
private:
int a; // private data member
public:
int b; // public data member
void getdata() //member function defined
{ cout< ”\n Enter the value of A and B: ”;
cin>>a>>b;
}
void output()
{
cout<<”\n Total=”<<a+b;
}
};
void main()
{
Addition obj;
obj.getdata(); // Input: Enter the value of A and B: 4 6
obj.b=11 // Public member can be accessed outside the class
// obj.a=12  Error: Private member cannot be accessed outside the class
obj.output(); // Output: Total=15 Why!? Answer is suppose to be: Total=10
}

Nesting of member functions


A member function of a class can be called in two ways.
1. Using an object of that class with dot operator
2. Using a member function of that class.
Thus, when a member function calls another member function of same class, it is called as nested
functions.

// To find the greatest of two numbers using nested functions:


#include <iostream.h>
#include<conio.h>
class largest
{
private:
int a,b;
public:
void getdata();
int findlarge();
void display();
};
void largest::getdata()
{
cout<<"Enter two numbers: ";
cin>>a>>b;
}
int largest::findlarge()
{
if(a>b)
return a;
else
return b;
}
void largest::display()
{
cout<<"Largest = "<<findlarge();
}
int main()
{
largest L; Enter two numbers: 20 10
L.getdata(); Largest = 20
L.display();
return 0;
}

Array as data members of a class


Arrays can be used as data members of a class as other data members.
#include<iostream.h>
class Array
{
private:
int a[10], n;
public:
void input();
void output();
};
void Array::input()
{
cout<<"\n Enter Array Size ";
cin>>n;
cout<<"Enter ”<< n <<” elements: ";
for(int i=0; i<n; i++)
cin>>a[i];
}
void Array::output()
{
cout<<"The array Elements are:";
for(int i=0; i<n; i++)
cout<< a[i];
}
void main()
{
Array Ar;
Ar.input();
Ar.output();
}

Array of objects
An array is a collection of elements of same data type.
We can create a number of objects of a class. These objects can be stored as an array of objects.
Any possible operation performed on array can also be performed on array of objects.
Example: class student
{
private:
int regno;
char name[10];
public:
void getdata();

} stud1,stud2,stud3,stud4,stud5;

or student stud[10];

Example Program: An array of Objects used to store student information


#include<iostream.h>
#include<iomanip.h>
class student
{
private:
int regno;
char name[20];
int marks[6];
public:
void getdata();
void showdata();
};
void student::getdata()
{
cout<<"\n Enter the regno: ";
cin>>regno;
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter Six subject marks: ";
for(int i=0; i<6; i++)
cin>>marks[i];
}
void student::showdata()
{
cout<<" \n Reg. No: "<<regno;
cout<<" \n Name: " <<name;
cout<<" \n Marks:";
for(int i=0; i<6; i++)
cout<<setw(4)<<marks[i];
}
void main()
{
student s[100];
for(int i=0; i<5; i++)
s[i].getdata();
for(i=0; i<5; i++)
s[i].showdata();
}

Passing objects to functions:


As like we pass variables of other data types as parameters, we can also pass objects as parameters
to functions.
Example program: To add two amounts by passing objects as parameters
#include<iostream.h>
#include<iomanip.h>
class amount
{
private:
int r, p;
public:
void getamount(int rp, int ps)
{
r = rp;
p = ps;
}
void add(amount a1, amount a2) //Objects are passed as parameters
{
r = a1.r + a2.r;
p = a1.p + a2.p;
if(p > 99)
{
p = p - 100;
r++;
}
}
void display()
{
cout<<r<<" Rupee and "<<p<<" Paise";
}
};
void main()
{
amount A1, A2, S;
A1.getamount(5, 90); // 5 Rupee 90 Paise
A2.getamount(6, 50); // 6 Rupee 50 Paise
S.add(A1, A2); // Objects are actual arguments
S.display(); // Output: 12 Rupee and 40 Paise
}

Differences between struct and classes in C++


In C++, a structure is defined with the keyword struct. Its members are public by default.
A class is defined with the keyword class. Its members are private by default. These are the
main differences between a structure and a class in C++.
Note: In C++, a structure can have both variables and functions as members (as we refer to them
in a class as: data members and member functions). Also, we can declare some of its members as
private, to restrict direct access from external functions as like in class.

You might also like