Oopm (Cs305) Unit-2 Notes
Oopm (Cs305) Unit-2 Notes
Encapsulation
The wrapping up of data and functions into a single unit (called class) is known as encapsulation. The data is
not accessible to the outside world, only those functions which are wrapped in the class can access it. These
functions provide the interface between
tween the object’s data and the program. This insulation of the data from
direct access by the program is called data hiding or information hiding. For example, as a driver you know
how to start the car by pressing the start button and internal details of the starting operations are hidden
from you.
Need of encapsulation
1. It improves the maintainability of an application.
2. Offers flexibility to the user to use the system very easily.
3. Helps the developers to organize the code better.
4. This method helps the developers to be more 'objective' and result oriented.
5. Encapsulated code is quite flexible and easy to change with new requirements.
6. Encapsulation makes unit testing easy.
7. It allows you to reduce coupling of modules and increases
increases cohesion inside a module as all piece of one
thing are encapsulated in one place.
8. Encapsulation helps you to change a part of code without affecting other parts of the code.
9. Improves the code readability of the application.
10. Enhanced security and makes maintenance of application easier.
// Program to demonstrate encapsulation
#include<iostream>
using namespace std;
class Encapsulation
{
private:
int x; // data hidden from outside world
OOP&M CS 305 UNIT II
public:
void set (int a) // function to set value of variable x
{
x =a;
}
int get () // function to return value of variable x
{
return x;
}
};
int main () // main function
{
Encapsulation obj;
obj.set(5);
cout<<obj.get ();
return 0;
}
OUTPUT: 5
In the above program the variable x is made private. This variable can be accessed and manipulated only using
the functions get () and set () which are present inside the class. Thus, we can say that here, the variable x
and the functions get () and set () are grouped together which is nothing but encapsulation.
Benefits of encapsulation
A. Encapsulation allows access to a level without revealing the complex details below that level.
B. Encapsulation protects an object from unwanted access.
C. Encapsulated classes are easier to change: We can change the privacy of the data according to the
requirement without changing the whole program by using access modifiers (public, private, protected).
For example, if a data member is declared private and we wish to make it directly accessible from
anywhere outside the class, we just need to replace the specifier private by public.
D. Simplifies the maintenance of the application.
Data abstraction
Abstraction refers to the act of representing essential features without including the background details or
explanation. Classes use the concept of abstraction and are defined as a list of abstract attributes for example:
size, weight and cost. Class also having function to operate on these attributes. They encapsulate all the
essential properties of the object that are to be created.
The attributes are also called as data members because they hold information. The functions that operate on
these data are called methods or member function.
For example, your program can make a call to the sort() function without knowing that what algorithm the
function actually uses to sort the given values. We can take another example like when you send an email to
someone you just click send and you get the success message, what actually happens when you click send,
how data is transmitted over network to the recipient is hidden from you (because it is irrelevant to you).
Another real-life example of abstraction is ATM Machine; All are performing operations on the ATM machine
2
OOP&M CS 305 UNIT II
like cash withdrawal, money transfer, retrieve mini-statement, but we can't know internal details about ATM.
Need of abstraction
Here, are the main reasons why abstraction is needed for Object-Oriented programming:
Helps you to simplify the representation of the domain models.
Abstraction hides the irrelevant details found in the code.
Abstraction helps you to partition the program into many independent concepts.
Offers the greatest flexibility when using ADT (Abstract Data Type) objects in different situations.
Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider
the pow () method present in “math.h” header file. Whenever we need to calculate power of a number, we
simply call the function pow () present in the “math.h” header file and pass the numbers as arguments
without knowing the underlying algorithm according to which the function is actually calculating power of
numbers.
Abstraction using access specifiers: Access specifiers are the main pillar of implementing abstraction in C++.
We can use access specifiers to enforce restrictions on class members.
For example:
Members declared as public in a class, can be accessed from anywhere in the program.
Members declared as private in a class, can be accessed only from within the class. They are not allowed
to be accessed from any part of code outside the class.
3
OOP&M CS 305 UNIT II
int main ()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return 0;
}
OUTPUT: a = 10, b = 20
You can see in the above program we are not allowed to access the variables a and b directly, however one
can call the function set () to set the values in a and b and the function display () to display the values of a
and b.
4
OOP&M CS 305 UNIT II
Behavior of the object- The behavior or operations of an object are its predefined functions. For example,
a television can show picture, change channels, tune for a channel etc. in object-oriented programming
terminology the behavior is implemented through methods.
Object Identity- Each object is uniquely identifiable. For example, the fridge cannot become the television.
Classes: Identifying classes and candidates for classes attributes and services
Class: 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 class is like a blueprint for an object.
For example: Consider the class of cars. There may be many cars with different names and model but all of
them will share some common properties like all of them will have 4 wheels, speed limit, mileage range etc.
So here, car is a class and wheels, speed limits, mileage are properties of class.
class car
{
public:
string name;
string model;
float speedlimit;
int wheels;
float mileage;
void get details () { }
};
int main ()
{
car c1; // c1 is an object
}
Identifying classes:
It’s a process that one gets better at over time. For example, it’s not unusual for inexperienced designers to
identify too many classes. Modeling too many classes result in poor performance, unnecessary complexity
and increased maintenance. On the other hand, too few classes tend to increase couplings and make classes
larger.
OOP&M CS 305 UNIT II
Example:
Candidate Classes Design Classes
Student Student
Teacher Professor
Class Course
Subject Assessment
Grades
Tests
Table 2.2: Identifying Candidate Classes
Access modifiers
Access modifiers or Access specifiers in a class are used to set the accessibility or visibility of the class
members.
It can set some restrictions on the class members not to get directly accessed by the outside functions.
Note: The default access specifier for members and classes is “private”.
6
OOP&M CS 305 UNIT II
class stat {
int code;
static int count; // static data member
public:
stat() {
code = ++count;
}
void showcode() {
cout << "\n\tObject number is :" << code;
}
int stat::count;
void main () {
clrscr();
stat obj1, obj2;
stat::showcount();
obj1.showcode();
stat ::showcount();
obj2.showcode();
getch();
}
Output
Count Objects: 2
Object Number is: 1
Count Objects: 2
Object Number is: 2
7
OOP&M CS 305 UNIT II
Instances
An instance, in object-oriented programming (OOP), is a specific realization of any object. An object may be
varied in a number of ways. Each realized variation of that object is an instance. The creation of a realized
instance is called instantiation.
Object can also be called as runtime instance of a class. It is used to access data and function members while
a program is running. Class specification provides only a template. It does not create any memory space for
the object. To create memory space at runtime, we need to create instance of the class, which is essentially
the class object.
Message passing
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. Message passing involves specifying the name of the object, the name of
the function and the information to be sent.
Message passing is nothing but sending and receiving of information by the objects same as people exchange
information. So, this helps in building systems that simulate real life. In OOPs, message passing involves
specifying the name of objects, the name of the function and the information to be sent. Following are the
basic steps in message passing.
Creating classes that define objects and its behavior.
Creating objects from class definitions.
Establishing communication among objects.
Construction rules
1. Call the constructor/initializer for each data member, in sequence.
2. Call the constructor for the class.
8
OOP&M CS 305 UNIT II
2) Call the constructor/initializer for each data member of the derived class, in sequence.
3) Call the constructor for the derived class
Object destruction
It is generally the case that after an object is not used, it is removed from memory to make room for other
programs or objects to take that object's place. However, if there is sufficient memory or a program has a
short run time, object destruction may not occur, memory simply being deallocated at process termination.
In some cases, object destruction simply consists of deallocating the memory, particularly in garbage-
collected languages, or if the "object" is actually a plain old data structure.
In other cases, some work is performed prior to deallocation, particularly destroying member objects (in
manual memory management), or deleting references from the object to other objects. This may be
automatic, or a special destruction method may be called on the object.
Destruction rules
When an object is deleted, the destructors are called in the opposite order.
The rules for an object of a derived class are:
1. Call the destructor for the derived class.
2. Call the destructor for each data member object of the derived class in reverse sequence.
3. Call the destructor for the base class.
Constructor
A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is
automatically called when object (instance of class) created. It is special member function of the class.
Compiler identifies a given member function is a constructor by its name and the return type. Constructor
has the same name as that of the class and it does not have any return type. Also, the constructor is always
public.
For example:
class A
{
public:
int x;
A() // constructor
{
// object initialization
}
};
9
OOP&M CS 305 UNIT II
1) Default constructor: Default constructor is the constructor which doesn’t take any argument. It has no
parameters
// Program to demonstrate default constructor
#include <iostream>
using namespace std;
class Defaultconstructor {
private:
int num1, num2 ;
public:
Defaultconstructor() {
num1 = 10;
num2 = 20;
}
void display () {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
int main () {
Defaultconstructor obj;
obj.display();
return 0;
}
Output: Num1=10, Num2=20
10
OOP&M CS 305 UNIT II
y = y1;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main ()
{
// Constructor called
Point p1(10, 15);
return 0;
}
Output: - P1.x=10
P1.y=15
3) Copy constructor: A copy constructor is a member function which initializes an object using another
object of the same class. Whenever we define one or more non-default constructors (with parameters)
for a class, a default constructor (without parameters) should also be explicitly defined as the compiler
will not provide a default constructor in this case. However, it is not necessary but it’s considered to be
the best practice to always define a default constructor.
11
OOP&M CS 305 UNIT II
Destructor
Destructor is a member function which destructs or deletes an object. Destructors have same name as the
class preceded by a tilde (~). Destructors don’t take any argument and don’t return anything. There can only
one destructor in a class with class name preceded by ~. If we do not write our own destructor in class,
compiler creates a default destructor for us.
The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a
class contains a pointer to memory allocated in class, we should write a destructor to release memory before
the class instance is destroyed. This must be done to avoid memory leak. It is always a good idea to make
destructors virtual in base class when we have a virtual function.
A destructor function is called automatically when the object goes out of scope:
1) The function ends
2) The program ends
3) A block containing local variables ends
4) A delete operator is called.
Destructor rules
1) The name of the destructor must begin with the tilde character (~).
2) The rest of the destructor name must be identical to the name of its class.
3) You must not include any return type, not even void.
4) A class can have no more than one destructor.
5) If you omit the destructor, the compiler automatically creates one for you. The destructor cannot have
any parameters.
6) The class destructor is automatically invoked when the instance of that class goes out of scope.
12
OOP&M CS 305 UNIT II
int main ()
{
BaseClass des; // Object Declaration for BaseClass
return 0;
}
Output: -
Constructor of the BaseClass : Object Created
Destructor of the BaseClass : Object Destroyed
13