0% found this document useful (0 votes)
43 views13 pages

Oopm (Cs305) Unit-2 Notes

Uploaded by

tanmaysj16
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)
43 views13 pages

Oopm (Cs305) Unit-2 Notes

Uploaded by

tanmaysj16
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/ 13

OOP&M CS 305 UNIT II

Mahakal Institute of Technology,Ujjain


Object Oriented Programming & Methodology (CS-305)
Class Notes
UNIT- II

Syllabus: Encapsulation and Data Abstraction


Abstraction- Concept of Objects: State, Behavior & Identity of an object;
Classes: identifying classes and candidates for Classes Attributes and Services, Access modifiers, Static
members of a Class, Instances, Message passing, and Construction and destruction of Objects.

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.

Figure 2.1: Encapsulation

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.

Below are some ways to implement abstraction:


Abstraction using Classes: We can implement abstraction in C++ using classes. Class helps us to group data
members and member functions using available access specifiers. A class can decide which data member will
be visible to outside world and which is not.

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.

// Program to demonstrate abstraction


#include <iostream>
using namespace std;
class implementAbstraction
{
private:
int a, b;
public:
void set (int x, int y) // method to set values of private members
{
a = x;
b = y;
}
void display ()
{
cout<<"a = " <<a << endl;
cout<<"b = " << b << endl;
}
};

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.

Advantages of data abstraction:


1. Avoids code duplication and increases reusability.
2. Can change internal implementation of class independently without affecting the user.
3. Helps to increase security of an application or program as only important details are provided to the user.

Difference between Abstraction and Encapsulation


S no. Abstraction Encapsulation
Encapsulation is a method to bind the data in a
Abstraction is the method of hiding the
1. single entity or unit along with a method to protect
unwanted information.
information.
We can implement abstraction using abstract Encapsulation can be implemented by creating a
2.
class and interfaces. Class.
Here implementation complexities are hidden In encapsulation, the data is hidden using
3.
using abstract classes and interfaces. methods of getters and setters.
In abstraction, problems are solved at the In encapsulation, problems are solved at the
4.
design or interface level. implementation level.
Encapsulation enables you to bind the code and
Abstraction allows you to focus on what the
5. data into a single unit to secure the data from the
object does instead of how it does it
outside world.
6. Focus mainly on what should be done. Focus primarily on how it should be done.
Table 2.1: Difference between Abstraction and Encapsulation

Concept of Objects: State, Behavior & Identity of an object


Object: An object is an identifiable entity with some characteristics and behavior. An object is an instance of
a class. When a class is defined, no memory is allocated but when it is instantiated (i.e., an object is created)
memory is allocated. When a program is executed, the objects interact by sending messages to one another.

The main purposes of using objects are as follows:


1) They correspond to the real-life entities.
2) They provide interactions with the real world.
3) They provide practical approach for the implementation of the solution.

4
OOP&M CS 305 UNIT II

All the objects have a state, behavior and identity.


 State of an object- The state or attributes are the built-in characteristics or properties of an object. For
example, a television has the size, color, and model.

 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.

Figure 2.2: State, Behavior & Identity of an object

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

Candidates for classes attributes and services:


 Attributes define the characteristics of the class that, collectively, capture all the information about the
class.
 To find candidates for classes begin with class modeling - an initial list of classes from which the actual
design classes will emerge.
 Candidate classes exists for the sole purpose of deriving the design classes. Design classes are the classes
that are modeled. Initially, there will be a lot of candidate classes. However, through analysis, their
number will be reduced as they are dropped, combined and merged.

Identify Candidate Classes


Candidate classes can be discovered by using CRC (Class, Responsibility & Collaboration).
 The aim of using CRC is to discover the real-world objects in a system and map the collaboration among
classes and their responsibilities.
 Once the list has been created, analyze the candidate classes for associations with other classes. Look for
collaborating classes.
 To identify how does each class relate to each other and to the process, when a class is kept, move it to
the list of design classes.

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.

There are 3 types of access modifiers available in C++:


A. Public: All the class members declared under public will be available to everyone. The data members and
member functions declared public can be accessed by other classes too. The public members of a class
can be accessed from anywhere in the program using the direct member access operator (.) with the
object of that class.
B. Private: The class members declared as private can be accessed only by the functions inside the class.
They are not allowed to be accessed directly by any object or function outside the class. Only the member
functions or the friend functions are allowed to access the private data members of a class.
C. Protected: Protected access modifier is similar to that of private access modifiers, the difference is that
the class member declared as protected are inaccessible outside the class but they can be accessed by
any subclass (derived class) of that class.

Note: The default access specifier for members and classes is “private”.

6
OOP&M CS 305 UNIT II

Consider a real-life example:


The Indian secret information system having 10 senior members have some top secret regarding national
security. So, we can think that 10 people as class data members or member functions who can directly access
secret information from each other but anyone can’t access this information other than these 10 members
i.e., outside people can’t access information directly without having any privileges. This is called data hiding.

Static members of a class


Static data members: Static is a keyword which is used to declare a special type of a variable or a function
inside or outside of a class.
A variable declared inside the class with static keyword is called static data member.

// Program to demonstrate static members of a class


#include<iostream.h>
#include<conio.h>

class stat {
int code;
static int count; // static data member

public:

stat() {
code = ++count;
}
void showcode() {
cout << "\n\tObject number is :" << code;
}

static void showcount() // static member function


{
cout << "\n\tCount Objects :" << count;
}
};

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

Characteristics of static member functions are:


 A static member function can only have access to other static data members and functions declared in
the same class.
 A static member function can be called using the class name with a scope resolution operator instead of
object name.
 Global functions and data may be accessed by static member function.
 A static member function does not have this Pointer.
 There cannot be a static and a non-static version of the same function.
 They cannot be declared as const or volatile.
 A static member function may not be virtual.

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 and destruction of objects


The process of initializing and starting up an object is called construction. The opposite of this is the process
of tearing down an object and cleaning it up, which is called destruction or finalization. Construction occurs
either when an object is being initialized or upon first reference to a type.

Construction rules
1. Call the constructor/initializer for each data member, in sequence.
2. Call the constructor for the class.

The rules for constructing an object of a derived class are:


1) Call the constructor for the base class (which recursively calls the constructors needed to completely
initialize the base class object.)

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
}
};

Rules for constructors


1) Constructor should be same name as the class and declared in the public section of the class.
2) Constructors are invoked automatically whenever the object is created.
3) Constructors do not have return type.
4) Constructor cannot be inherited, but from the derived class we can call the base class constructors.
5) Constructor cannot be virtual.
6) It is not possible to refer to the address of constructors.
7) It is not possible to use the constructor as member of union if the object is created with constructor.

9
OOP&M CS 305 UNIT II

Types of constructors in C++


1) Default constructor
2) Parameterized constructor
3) Copy constructor

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

2) Parameterized constructor: It is possible to pass arguments to constructors. Typically, these arguments


help initialize an object when it is created. To create a parameterized constructor, simply add parameters
to it the way you would to any other function. When you define the constructor’s body, use the
parameters to initialize the object.
// Program to demonstrate parameterized constructor
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point (int x1, int y1)
{
x = x1;

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);

// Access values assigned by constructor


cout << "p1.x = " << p1. getX() << ", p1.y = " << p1.getY();

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.

// Program to demonstrate copy constructor


#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point (int x1, int y1) { x = x1; y = y1; }
// Copy constructor
Point (const Point &p2) {x = p2.x; y = p2.y; }
int getX() { return x; }
int getY() { return y; }
};
int main ()
{

11
OOP&M CS 305 UNIT II

Point p1(10, 15); // Normal constructor is called here


Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1. getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2. getX() << ", p2.y = " <<p2.getY();
return 0;
}
Output: -
P1.x=10, P1.y=15
P2.x=10, P2.y=15

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.

// Program to demonstrate destructor


#include<iostream>
using namespace std;

class BaseClass // Class Name


{
public:

BaseClass() //Constructor of the BaseClass


{

12
OOP&M CS 305 UNIT II

cout << "Constructor of the BaseClass : Object Created"<<endl;


}

~BaseClass () //Destructor of the BaseClass


{
cout << "Destructor of the BaseClass : Object Destroyed"<<endl;
} };

int main ()
{
BaseClass des; // Object Declaration for BaseClass
return 0;
}
Output: -
Constructor of the BaseClass : Object Created
Destructor of the BaseClass : Object Destroyed

Difference between Constructor and Destructor


S no. Constructor Destructor
Constructor helps to initialize the object of a
1. Destructor is used to destroy the object of a class.
class.
It is declared as Classname (arguments if Destructor is declared as ~ClassName (no
2.
any){Constructor’s Body}. arguments) { }.
Constructor can accept the arguments or can be
3. Destructor can’t have any argument.
without arguments.
A constructor is called when the instance or Destructor is called automatically when program
4.
object of the class is created. terminates.
Constructor is used to allocate the memory to Destructor is used to deallocate the memory of
5.
an instance or object. an object of a class.
6. Constructor can be overloaded. It can’t be overloaded.
The constructor’s name is same as the class Destructor’s name is also same as the class name
7.
name. preceded by tiled (~) operator.
8. In a class, there can be multiple constructors. In a class, there is always a single destructor.
Table 2.3: Difference between Constructor and Destructor

13

You might also like