0% found this document useful (0 votes)
14 views27 pages

OOP-Unit 2

Uploaded by

vekariyajay985
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)
14 views27 pages

OOP-Unit 2

Uploaded by

vekariyajay985
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/ 27

UNIT – 2:

Data Encapsulation
and inheritance
Unit – 2. Data Encapsulation and inheritance

2.1 Access controls concepts


Access modifiers are used to implement an important aspect of Object-Oriented Programming
known as Data Hiding.

In C++, there are three access specifiers:

public - The public access specifier is used to specify that a class member can be accessed from
anywhere, both inside and outside the class. This means that any function or object can access
the public members of the class. The public members of a class are typically used to represent
the interface of the class.

private - The private access specifier is used to specify that a class member can only be
accessed from within the class. This means that any function or object outside the class cannot
access the private members of the class. The private members of a class are typically used to
represent the implementation of the class and are hidden from the outside world.

protected - The protected access specifier is used to specify that a class member can be
accessed from within the class and its derived classes. This means that any function or object
outside the class hierarchy cannot access the protected members of the class. The protected
members of a class are typically used to represent the implementation of a class that should be
accessible to its derived classes.

2
Unit – 2. Data Encapsulation and inheritance

2.2 Declaring simple class, member variables and member functions.

 Specifying a Class

A class in C++ combines related data and functions together. It makes a data type which
is used for creating objects of this type.
Classes represent real world entities that have both data type properties
(characteristics) and associated operations (behavior).
Generally a class specification has two parts :

 Class Declaration
 Class Function definition

Class Declaration

The syntax of a class definition is shown below :

class name_of _class


{
private :
variable declaration; // data member
Function declaration; // Member Function (Method)
protected:
Variable declaration;
Function declaration;
public :
variable declaration;
Function declaration;
};

Here, the keyword class specifies that we are using a new data type and is followed by the class
name.

The body of the class has two keywords namely :


(i) private(ii) public
In C++, the keywords private and public are called access specifiers. The data hiding
concept in C++ is achieved by using the keyword private. Private data and functions can only be
accessed from within the class itself. Public data and functions are accessible outside the class
also.
The data declared under Private section are hidden and safe from accidental
manipulation. Though the user can use the private data but not by accident.

3
Unit – 2. Data Encapsulation and inheritance

The functions that operate on the data are generally public so that they can be accessed from
outside the class but this is not a rule that we must follow.

 Class Function definition

In C++, the member functions can be coded in two ways :


(a) Inside class definition
(b) Outside class definition using scope resolution operator (::)
The code of the function is same in both the cases, but the function header is different as

Inside Class Definition:


When a member function is defined inside a class, we do not require to place a
membership label along with the function name. We use only small functions inside the class
definition and such functions are known as inline functions. In case of inline function the
compiler inserts the code of the body of the function at the place where it is invoked (called)
and in doing so the program execution is faster.

Outside Class Definition Using Scope Resolution Operator (::) :

In this case the function’s full name (qualified_name) is written as shown:

Name_of_the_class :: function_name

The syntax for a member function definition outside the class definition is :

return_type name_of_the_class::function_name (argument list) { body of function }

Here the operator :: known as scope resolution operator helps in defining the member function
outside the class. Earlier the scope resolution operator(::)was is use in situations where a global
variable exists with the same name as a local variable and it identifies the global variable.

Example of Class :

Class student
{
private:
char reg_no[10];
char name[30];
int age;
char address[25];
public :

4
Unit – 2. Data Encapsulation and inheritance

void init_data()//Inside Class Defenation


{
- - - - - //body of function - - - - -
}
void display_data(); //Only Declared the function
}; // End of Class

void student :: display_data()//Outside class Defination


{
----------//body of function -------
}

Int main()
{
student ob; //class variable (object) created
Ob.init_data(); //Access the member function
ob.display_data(); //Access the member function
}

2.3 Concepts and use of enum.

Enumeration is a user defined datatype in C/C++ language. It is used to assign names to the
integral constants which makes a program easy to read and maintain. The keyword “enum” is
used to declare an enumeration.

The following is the syntax of enums.


enum enum_name{const1, const2, ....... };

If we assign a float value to a character value, then the compiler generates an error. In the same
way, if we try to assign any other value to the enumerated data types, the compiler generates
an error. Enumerator types of values are also known as enumerators. It is also assigned by zero
the same as the array.

// Defining enum Year


enum year {
Jan,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,

5
Unit – 2. Data Encapsulation and inheritance

Sep,
Oct,
Nov,
Dec
};

int main()
{
int i;

// Traversing the year enum


for (i = Jan; i <= Dec; i++)
cout << i << " ";
return 0;
}

Output:-

0 1 2 3 4 5 6 7 8 9 10 11

2.4 Concepts of Data hiding, abstraction and encapsulation

Encapsulation
The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class.
The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it. These functions provide the interface between the object’s
data and the program.
This wrapping of the data from direct access by the program is called data hiding or
information hiding.

Features of Encapsulation
1) We cannot access any function from the class directly. We need an object to access that
function that is using the member variables of that class.
2) The function which we are making inside the class must use only member variables, only
then it is called encapsulation.
3) If we don’t make a function inside the class which is using the member variable of the
class then we don’t call it encapsulation.
4) Increase in the security of data
5) It helps to control the modification of our data members.

6
Unit – 2. Data Encapsulation and inheritance

class Encapsulation {
private:
int x; // Data hidden from outside world

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()
{
Encapsulation obj;
obj.set(5);
cout << obj.get();
return 0;
}

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 Data Members and
function operate on these Data Members. They encapsulate all the essential properties of the
object that are to be created.
The functions that operate on these data are sometimes called methods or member
function.

Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerator will increase the speed of the car or applying brakes will stop the car but he does
not know how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in
the car. This is what abstraction is.

7
Unit – 2. Data Encapsulation and inheritance

Advantages of Data Abstraction


1) Helps the user to avoid writing the low-level code
2) Avoids code duplication and increases reusability.
3) Can change the internal implementation of the class independently without affecting
the user.
4) Helps to increase the security of an application or program as only important details are
provided to the user.
5) It reduces the complexity as well as the redundancy of the code, therefore increasing
the readability.

#include<iostream>
using namespace std;

class bank
{
float amt,rate,year;
float si; //Simple interest
float NetAmt;

public:
void read ()
{
cout <<" Enter Principle Amount :: ";
cin>>amt ;
cout<<"\n Enter Rate of Interest :: ";
cin>>rate;
cout <<"\n Enter Number of years :: ";
cin>>year;

si= (amt * rate * year) /100;


NetAmt = si + amt;

}
void show()
{
cout <<"\n\n Interest : "<<si;
cout <<"\n\n Total Amount : "<<NetAmt<<"\n";
}
};

int main ()
{

8
Unit – 2. Data Encapsulation and inheritance

bank b;
b.read();
b.show();
return 0;
}

Data Hiding
Data hiding is a technique of hiding internal object details, i.e., data members. It is an object-
oriented programming technique. Data hiding ensures, or we can say guarantees to restrict the
data access to class members. It maintains data integrity.

Data hiding means hiding the internal data within the class to prevent its direct access from
outside the class.

Data hiding also helps to reduce the system complexity to increase the robustness by limiting
the interdependencies between software components. Data hiding is achieved by using the
private access specifier.

#include<iostream>
using namespace std;
class ABC
{
int num; //by default private
public:
void read();
void print();

};

void ABC :: read()


{
cout<<"Enter any Integer value"<<endl;
cin>>num;
}

void ABC :: print(){


cout<<"The value is "<<num<<endl;
}

int main()
{
ABC obj;
obj.read();

9
Unit – 2. Data Encapsulation and inheritance

obj.print();

return 0;
}

Difference between Data Hiding and Encapsulation

Data Hiding Encapsulation

It is associated with data security. It can be defined as the wrapping up of data


into a single module.

It also helps conceal the complexities of the This will hide the complicated and
application. confidential information about the
application.

It focuses on hiding/restricting the data It focuses on hiding the complexity of the


usage. system.

It is considered as a process and a It is considered as a sub−process in the bigger


technique. process of data hiding.

The data is always private and inaccessible. The encapsulated data can be private or
public, depending on the requirement.

Friend Function
Friend functions of the class are granted permission to access private and protected members
of the class in C++. They are defined (Body part) globally outside the class scope. Friend
functions are not member functions of the class. So, what exactly is the friend function?

A friend function in C++ is a function that is defined outside a class but is capable of accessing
the private and protected members of the class. There could be situations in programming
wherein we want two classes to share their members. These members may be data members,
class functions. In such cases, we make the desired function, a friend to both these classes
which will allow accessing private and protected data members of the class.

Generally, non-member functions cannot access the private members of a particular class.
Once declared as a friend function, the function is able to access the private and the protected
members of these classes.

10
Unit – 2. Data Encapsulation and inheritance

Characteristics of Friend Function

 A friend function is not in the scope of the class n which it has been declared as friend.
 It cannot be called using the object of that class.
 It can be invoked like a normal function without any object.
 Unlike member functions, it cannot use the member names directly.
 It can be declared in public or private part without affecting its meaning.
 Usually, it has objects as arguments.

#include<iostream>
using namespace std;

class abc
{
int x,y;
public:
void setdata (int no1, int no2)
{
x=no1;
y=no2;
}
friend void max (abc); //friend function.
};

void max (abc a1)


{
if (a1.x > a1.y)
cout<<"Big No is : "<< a1.x <<"\n";
else
cout<<"Big No is : "<< a1.y <<"\n";
}
int main ()
{
abc a;
a.setdata (10,20);
max (a);
return 0;
}

11
Unit – 2. Data Encapsulation and inheritance

2.5 Concepts of Inheritance and Types of Inheritance


One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code
functionality and fast implementation time.

When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the members of an
existing class. This existing class is called the base class, and the new class is referred to as
the derived class.

The idea of inheritance implements the is a relationship. For example, mammal IS-A animal,
dog IS-A mammal hence dog IS-A animal as well and so on.

Base & Derived Classes:


A class can be derived from more than one classes, which means it can inherit data and
functions from multiple base classes. To define a derived class, we use a class derivation list to
specify the base class. A class derivation list names one or more base classes and has the form:

Class derived-class: access-specifier base-class

Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. If the access-specifier is not used, then it is private by default.

Access Control and Inheritance:


A derived class can access all the non-private members of its base class. Thus base-class
members that should not be accessible to the member functions of derived classes should be
declared private in the base class.

Rules for inheritance :

1. Private variables/methods will not be accessed in child class.


2. Child inherits parent = protected;[parent protected & public]=protected
3. Child inherits parent = private;[parent protected & public]=private
4. Child inherits parent = public;[parent protected & public]=[protected & public]

We can summarize the different access types according to who can access them in the
following way:

12
Unit – 2. Data Encapsulation and inheritance

Access Public Protected private

Same class Yes Yes yes

Derived classes Yes Yes no

Outside classes Yes No no

A derived class inherits all base class methods with the following exceptions:

 Constructors, destructors and copy constructors of the base class.

 Overloaded operators of the base class.

 The friend functions of the base class.

Inheritance according to access specifier:


When deriving a class from a base class, the base class may be inherited through public,
protected or private inheritance. The type of inheritance is specified by the access-specifier as
explained above.

We hardly use protected or private inheritance, but public inheritance is commonly used.
While using different type of inheritance, following rules are applied:

 Public Inheritance: When deriving a class from a public base class, public members of
the base class become public members of the derived class and protected members of
the base class become protected members of the derived class. A base
class's private members are never accessible directly from a derived class, but can be
accessed through calls to the public and protected members of the base class.

 Protected Inheritance: When deriving from a protected base class, public and
protected members of the base class become protected members of the derived class.

 Private Inheritance: When deriving from a private base class, public and
protected members of the base class become private members of the derived class.

13
Unit – 2. Data Encapsulation and inheritance

Types of Inheritance

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)

Single Inheritance

In this type of inheritance one derived class inherits from only one base class. It is the most
simplest form of Inheritance.

Example:
Class A //Base class OR Parent Class
{
//class body
};
class B : public A //Derived class OR Child Class
{

//class body

};

14
Unit – 2. Data Encapsulation and inheritance

Multiple Inheritance

In this type of inheritance a single derived class may inherit from two or more than two base
classes.

Class A //1st base class


{
//class body
};
class B //2nd base class
{

//class body

};

Class C : public A,public B //derived from 2 base classes A and B

//class body

};

15
Unit – 2. Data Encapsulation and inheritance

Hierarchical Inheritance

In this type of inheritance, multiple derived classes inherits from a single base class.

Class A //base class


{
//class body
};

class B : public A //derived from class A


{
//class body
};

class C : public A //derived from class A


{
//class body
};

class D : public A //derived from class A


{
//class body
};

16
Unit – 2. Data Encapsulation and inheritance

Multilevel Inheritance

In this type of inheritance the derived class inherits from a class, which in turn inherits from some other
class. The Super class for one, is sub class for the other.

Class A //1st base class


{
//class body
};
class B:public A //derived from class A
{

//class body

};

Class C:public B //derived class B

//class body

};

17
Unit – 2. Data Encapsulation and inheritance

Hybrid Inheritance
Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.

Class A //base class


{
//class body
};
class B:public A //derived from class A
{

//class body

};

class C:public A //derived from class A

//class body

};

class D:public B,public C //derived from class B and C

//class body

};

18
Unit – 2. Data Encapsulation and inheritance

1.6 Constructors

Constructor in C++ is a special method that is invoked automatically at the time of


object creation. It is used to initialize the data members of new objects generally. The
constructor in C++ has the same name as the class or structure. Constructor is invoked at the
time of object creation. It constructs the values i.e. provides data for the object which is why
it is known as constructors.

Types of Constructor
There are three types of constructor are there as per following.
1. Default Constructor
1.1 Compiler Define Default Constructor : A default constructor in C++ is a type of
constructor that is implicitly created by the compiler when no constructor is
created explicitly in a class.
2.1 User Define Default Constructor : A constructor without any arguments or with
the default value for every argument is said to be the User Define Default
constructor. A constructor that has zero parameter list or in other sense, a
constructor that accept no arguments is called a zero argument constructor or
default constructor. If default constructor is not defined in the source code by
the programmer, then the compiler defined the default constructor implicitly
during compilation.
2. Parameterize Constructor : The parameterized constructors are the constructors
having a specific number of arguments to be passed. The purpose of a parameterized
constructor is to assign user-wanted specific values to the object variables (Data
Member) of different objects.
3. Copy Constructor : A copy constructor is a member function that initializes an object
using another object of the same class. In simple terms, a constructor which creates an
object by initializing it with an object of the same class, which has been created
previously is known as a copy constructor.
Copy constructor is used to initialize the members of a newly created object by copying
the members of an already existing object.
There are two types of Copy Constructors
3.1 Compiler Define / Implicit Copy Constructor: The compiler defines the default
copy constructor. If the user defines no copy constructor, compiler supplies its
constructor.
3.2 User Defined constructor: The programmer defines the user-defined
constructor.

 SPECIAL CHARACTERISTICS OF CONSTRUCTORS

These have some special characteristics. These are given below:


1) These are called automatically when the objects are created.
2) All objects of the class having a constructor are initialized before some use.

19
Unit – 2. Data Encapsulation and inheritance

3) These should be declared in the public section for availability to all the functions.
4) Return type (not even void) cannot be specified for constructors.
5) These cannot be inherited, but a derived class can call the base class constructor.
6) These cannot be static.
7) Default and copy constructors are generated by the compiler wherever required.
Generated constructors are public.
8) These can have default arguments as other C++ functions.
9) A constructor can call member functions of its class.
10) An object of a class with a constructor cannot be used as a member of a union.
11) A constructor can call member functions of its class.

Declaration and Definition of a Constructor:

It is defined like other member functions of the class, i.e., either inside the class
definition or outside the class definition. For example, the following program illustrates the
concept of a constructor:
There are two way to call constructor : 1) Implicit Call , 2) Explicit Call

//To demonstrate a default constructor


#include<iostream>
using namespace std;

class abc
{
int x,y;
public:
abc() //Default Constructor (User defined)
{
x=10; y=20;
cout<<"Default constructor is called\n";
}
void showdata()
{
cout<<"x = "<< x <<endl;
cout<<"y = "<< y <<endl;
}
};
int main()
{
abc a; //implicit call
abc b,c;
abc d = abc(); //explicit call

20
Unit – 2. Data Encapsulation and inheritance

a.showdata();
return 0;
}

Parameterize Constructor and Constructor Overloading Example


// Basic progrm to demostrate the parameterize constructor
// Constructore overloading
#include<iostream>
using namespace std;

class abc
{
int x,y;
public:
abc() //Default Constructor (User defined)
{
x=10; y=20;
cout<<"Default constructor is called\n";
}
abc(double no5) //Parameterize constructor
{
x=no1; y=no1+5;
}
abc(int no1) //Parameterize constructor
{
x=no1; y=no1+5;
}
abc(int no1,int no2) //Parameterize constructor
{
x=no1; y=no2;
}
void showdata()
{
cout<<"x = "<< x <<endl;
cout<<"y = "<< y <<endl;
}
};
int main()
{
abc a; //Default Constructor call
abc c(10); //Single parameter intger type constructor call
abc d(10.50); //Single parameter double type constructor call
abc e(10,12); //Two parameter intger type constructor call

21
Unit – 2. Data Encapsulation and inheritance

a.showdata();
return 0;
}

Constructor Overloading

When we implements (Use) multiple constructors in a class with different no of


parameters and different type of parameter with change of parameter order is called
constructor overloading. For example, consider the above program with overloaded
constructors for the ABC class:

 Copy Constructors

A copy constructor is a member function that initializes an object using another object of the
same class. In simple terms, a constructor which creates an object by initializing it with an
object of the same class, which has been created previously is known as a copy constructor.

Copy constructor is used to initialize the members of a newly created object by copying the
members of an already existing object.

There are two types of copy constructors are there.


1) Implicit Copy Constructor (Compiler Defined): When no copy constructor is defined in a
class and we try to copy one object’s value on other object of same class that time implicit copy
constructor is called that is provided by compiler.

2) Explicit Copy Constructor (User Defined): When user defined copy constructor is available
in a class and we try to copy one object’s value on other object of same class that time explicit
copy constructor is called that is defined by user in class.

It is of the form classname (classname &) and used for the initialization of an object form
another object of same type. For example,

Implicit Copy Constructor Example


#include <iostream>
using namespace std;

class abc
{
public:
int x;
int y;

22
Unit – 2. Data Encapsulation and inheritance

};

int main()
{
abc a;
a.x=10;a.y=20;
abc b (a); //call implicit copy (compiler defined) constructor
cout<<b.x<<"\n"<<b.y<<endl;
return 0;
}

Explicit Copy Constructor Example


#include <iostream>
using namespace std;
class abc
{
public:
int x;
int y;
abc() {}
abc (abc &a1) // User defined copy constructor
{
x=a1.x+5; y=a1.y+3;
cout<<"User Defined Copy Constructor called\n";
}
};

int main()
{
abc a;
a.x=10; a.y=20;
abc b = a; //Call user defined copy constructor
abc c(b); //Call user defined copy constructor
abc d;
d=a; //Do not Call copy constructor
return 0;
}

23
Unit – 2. Data Encapsulation and inheritance

Constructor with default argument

In C++, we can define constructor s with default arguments. For example, The following code
segment shows a constructor with default arguments:

Class add
{
Private:
int num1, num2, num3;
Public:
add(int=0,int=0); //Default argument constructor
void enter (int,int);
void sum();
void display();
};

//Default constructor definition


add::add(int n1, int n2)
{
num1=n1;
num2=n2;
num3=n0;
}
Void add ::sum()
{
num3=num1+num2;
}
Void add::display ()
{
Cout<<”\n The Sum of two number is “<< num3<<endl;
}

Now using the above code objects of type add can be created with no initial values, one initial
values or two initial values. For Example,

add obj1, obj2(5), obj3(10,20);

Here, obj1 will have values of data members num1=0, num2=0 and num3=0

obj2 will have values of data members num1=5, num2=0 and num3=0

obj3 will have values of data members num1=10, num2=20 and num3=0

24
Unit – 2. Data Encapsulation and inheritance

If two constructors for the above class add are

Add::add() {} //default constructor

and add::add(int=0); //default argument constructor

Then the default argument constructor can be invoked with either two or one or no
parameter(s).

Without argument, it is treated as a default constructor-using these two forms together causes
ambiguity. For example,

The declaration add obj;

is ambiguous i.e., which one constructor to invoke i.e.,

add :: add()

or add :: add(int=0,int=0)

so be careful in such cases and avoid such mistakes.

Destructor

Declaration and Definition of a Destructor

The syntax for declaring a destructor is :

~name_of_the_class() { }

So the name of the class and destructor is same but it is prefixed with a ~ (tilde). It does not
take any parameter nor does it return any value. Overloading a destructor is not possible and
can be explicitly invoked. In other words, a class can have only one destructor. A destructor can
be defined outside the class. The following program illustrates this concept :

//Illustration of the working of Destructor function


#include<iostream>
using namespace std
class add
{
private :
int num1,num2,num3;

25
Unit – 2. Data Encapsulation and inheritance

public :
add(int=0, int=0); //default argument constructor
void sum();
void display();
~ add(void); //Destructor
};

//Destructor definition
~add() Add:: ~add(void) //destructor called automatically at end of program
{
Num1=num2=num3=0;
Cout<<”\nAfter the final execution, the object has entered in the destructor to destroy
object”;
}

//Constructor definition add()


Add::add(int n1,int n2)
{
num1=n1; num2=n2; num3=0;
}

//function definition sum ()


Void add::sum()
{
num3=num1+num2;
}

//function definition display ()


Void add::display () {
Cout<<”\nsum of two number is :”<<num3;
}

int main()
{
add obj1, obj2(5), obj3(10,20); //objects created and initialized
obj1.sum(); //function call
obj2.sum();
obj3.sum();
Cout<<”\n obj 1 : “;
Obj1.display();
Cout<<”\n obj2 : “;
Obj2.display();
Cout<<”\n obj 3:”;

26
Unit – 2. Data Encapsulation and inheritance

Obj3.display();
}

Destructor is an instance member function that is invoked automatically whenever an object is


going to be destroyed. Meaning, a destructor is the last function that is going to be called
before an object is destroyed.

Special Characteristics of Destructors

Some of the characteristics associated with destructors are :

1) A destructor is also a special member function like a constructor. Destructor destroys


the class objects created by the constructor.
2) Destructor has the same name as their class name preceded by a tilde (~) symbol.
3) It is not possible to define more than one destructor.
4) The destructor is only one way to destroy the object created by the constructor. Hence
destructor can-not be overloaded.
5) Destructor neither requires any argument nor returns any value.
6) It is automatically called when an object goes out of scope.
7) Destructor release memory space occupied by the objects created by the constructor.
8) In destructor, objects are destroyed in the reverse of an object creation.

27

You might also like