OOP-Unit 2
OOP-Unit 2
Data Encapsulation
and inheritance
Unit – 2. Data Encapsulation and inheritance
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
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
Here, the keyword class specifies that we are using a new data type and is followed by the class
name.
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.
Name_of_the_class :: function_name
The syntax for a member function definition outside the class definition is :
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
Int main()
{
student ob; //class variable (object) created
Ob.init_data(); //Access the member function
ob.display_data(); //Access the member function
}
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.
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.
5
Unit – 2. Data Encapsulation and inheritance
Sep,
Oct,
Nov,
Dec
};
int main()
{
int i;
Output:-
0 1 2 3 4 5 6 7 8 9 10 11
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:
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
#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;
}
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();
};
int main()
{
ABC obj;
obj.read();
9
Unit – 2. Data Encapsulation and inheritance
obj.print();
return 0;
}
It also helps conceal the complexities of the This will hide the complicated and
application. confidential information about the
application.
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
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.
};
11
Unit – 2. Data Encapsulation and inheritance
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.
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.
We can summarize the different access types according to who can access them in the
following way:
12
Unit – 2. Data Encapsulation and inheritance
A derived class inherits all base class methods with the following exceptions:
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 body
};
//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.
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 body
};
//class body
};
17
Unit – 2. Data Encapsulation and inheritance
Hybrid Inheritance
Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.
//class body
};
//class body
};
//class body
};
18
Unit – 2. Data Encapsulation and inheritance
1.6 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.
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.
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
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;
}
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
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.
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,
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;
}
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
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();
};
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,
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
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,
add :: add()
or add :: add(int=0,int=0)
Destructor
~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 :
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”;
}
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();
}
27