You are on page 1of 12

Data Hiding in C++ with Examples available.

So those bu ons are nothing but


In this ar cle, I am going to discuss Data Hiding func ons. And when you press the bu on,
in C++ with Examples. Please read our previous something happens inside the circuit board to
ar cle where we discussed How to Create respond to that par cular func on.
Objects in Heap Memory using C++ with
Examples. At the end of this ar cle, you will Similarly, if you take an example of a car
learn the objec ve of data hiding and why do everything is covered inside the bonnet and
you want to hide data. nothing is visible. Only the func ons are visible
that are at the dashboard and whatever the
Data Hiding in C++: opera on that you perform affects the engine
Let us learn about data hiding. This is one of the that is inside the bonnet. But you cannot access
important topics in object orienta on and data bonnet directly. You can access everything
hiding is related to encapsula on. A er through func ons that are accelera on and
encapsula on, we can also achieve data hiding. change of gear and all these things.
What does it mean? Let us see.

By observing the products of other


class Rectangle engineering, we can find that only the
{ func ons should be made public, and data
public: should be made private because if the data is
int length; public, we are able to directly create the object
int breadth; and access data.
int Area ()
{ Imagine it. we have a television box and there
return length * breadth; are some wires coming out of the box. The
} wires that are hanging out, now you can join
int Perimeter () those wires. Some func ons will be performed
{ if you join the wrong wires then the television
return 2 * (length + breadth); may not work properly.
}
}; Suppose a television belongs to your company.
A class will contain data and func ons. So, data I have purchased this television and I’m playing
members and member func ons are together with those wires. If something wrong happens
here inside this class. So by wri ng everything then who do I blame? Your company. You did
inside a block i.e. ‘{ }’ we are achieving not make this television properly. I was joining
encapsula on. But the problem here is we the wires only but the television is not working
have made everything as public, data as well as properly, so you will be blamed. You should not
func ons. have anything coming out of the television. For
all the func ons you provide bu ons but if
In our previous ar cles already we have given bu ons are not working then you are
some examples that if you see a television box, responsible. Because what is happening inside,
everything is kept inside the box and even I don’t know. I am a user. So, you should
there will be a warranty seal on the box and provide func ons and when I call those
what is visible outside? the bu ons that are func ons if it is not working properly then you
nothing but func ons. Press that bu on then are responsible for that.
the func on will be performed. Volume
change, volume will increase or decrease like
that. For all these opera ons bu ons are int main(){
Rectangle r; If data members are made public then there
r.length = 10; are chances that they may be mishandled. If
r.breadth = 12; mishandling is done the func ons of a class
} may not give the correct results and we cannot
rely on such classes, though it is a mistake of a
In the same way, here we are directly accessing programmer. But the class will also be blamed
variables of the class or data members of the equally for giving wrong results.
class. If this is your class and if anything goes
wrong then I will blame you. If you hide
everything and say you can access everything How to Achieve Data Hiding in C++ (Accessors
through a func on then you can control and Mutators)?
everything. We will make the data members private and
member func ons public,
We have discussed so many things related to
data hiding and we have given various class Rectangle
examples. Now let us see how these things are {
related. As in the ‘Rectangle’ class, we made private:
data members public then if I write, int length;
int breadth;
public:
r.length = -5; int Area ()
r.breadth = 10; {
return length * breadth;
Can length be nega ve? I don’t know. I’m just a }
user. I’m concentra ng on my main func on. I int Perimeter ()
don’t know what is ‘Rectangle’ class and I don’t {
even know that length and breadth can be return 2 * (length + breadth);
nega ve. Now if we write, }
};
cout << r.Area() << endl; From the point where we have wri en public,
everything below that becomes public. And
same with private. Here we have made data
What will be the output? -50. The area cannot members private. And by default, everything is
be nega ve. The area is nega ve because we private in a class. We can skip wri ng private
have set a nega ve length. So, I’m mishandling for data members as by default they are
things. The things are going wrong because you private.
have kept length and breadth public and you
are allowing me to access them. So, I can say Can we access length or breadth now?
that your class is wrong. Your class is not No, we cannot write the value of length or
perfect because it is giving nega ve areas. breadth and even we cannot read the value of
these variables. Then how we can set length
So, this is the philosophy behind object- and breadth? We cannot set it directly. If we
orienta on. If you think in this way, then you write,
can design classes properly. So that data
members should not be made public.
Rectangle r;
Why data members should not be made cout << r.Area() << endl;
public?
Rectangle r;
Now, what result we will get? See the object ‘r’ r.setLength(10);
is having its length and breadth r.setBreadth(14);
}
Data Hiding in C++ with Examples Here we have an object of type rectangle in our
main func on. Then we have called the
We have not ini alized the variables as we are ‘setLength’ and ‘setBreadth’ func ons and
not allowed to ini alize them. So, both the passed some values as parameters. ‘10’ will
variables will have some garbage value. Then if store in length and ‘14’ will store in breadth.
we print the area, the area func on will How to Achieve Data Hiding in C++ (Accessors
mul ply these two garbage values and give and Mutators)?
some garbage value. This is the problem. We
are unable to set that length and breadth then We have not directly set the value of length and
how to set these values? As we said that breadth but we are calling the func ons of a
func on should be public so there should be a class. So, this is a be er way. You can call the
‘set’ func on for se ng the length and func ons and set the values. So, it is a good
breadth. And also, when we want to read it prac ce but s ll, the problem is as it is. See if
there should be a ‘get’ func on for ge ng the we say
value of length and breadth. So, let’s write
those func ons. r.setBreadth(-5);

For se ng length, we have, It will take -5 and set it into the breadth and s ll
void setLength(int l){ breadth is -5 again. Then what is the benefit of
length = l; wri ng the func ons? Now we will make those
} func ons a li le smart by checking the data
This is the func on for se ng the length of the they are ge ng and then se ng it. Let us
rectangle. This is taking one parameter which is modify those func ons.
the length that we want to set. And inside this,
we assigned the value of ‘l’ to the length void setLength(int l){
variable. For se ng breadth, we have, if(l >= 0)
void setBreadth(int b){ length = l;
breadth = b; else
} length = 0;
Here we assigned the value of ‘b’ to the }
breadth variable. So, these are the se ers that void setBreadth(int b){
will set the given value of length and breadth. if(b >= 0)
Now let us write ge ers. breadth = b;
int getLength(){ else
return length; breadth = 0;
} }
int getBreadth(){
return breadth; Now the setLength func on is valida ng the
} data that it is ge ng. If ‘l’ is greater than 0 then
These are the ge er func ons for length and the only length will be assigned to the length
breadth. Both the func ons are of type ‘int’ as variable otherwise length will be 0. Same with
they are returning an integer value. Now how breadth func on. We can also write a
to use these func ons? Let us see. statement inside setLength or setBreadth
int main(){ func on that will inform us that the data is
invalid or nega ve. Now we have a setLength whatever the data member, if it is length then
and setBreadth func ons which validate the it would getLength, if it is breadth then it will
data and assign it. So, if we write, getBreadth, if it is marks then getMarks, if it is
prize then getPrize. These func ons are called
int main(){ Accessors and all the set func ons are called
Rectangle r; Mutators. Both the func ons se ers and
r.setLength(10); ge ers are known as property func ons.
r.setBreadth(-5); Because data numbers are called property. So,
cout << r.Area() << endl; these types of func ons are called property
} func ons, and the one which is reading the
value is called accessors and the one which is
Here we are passing -5, so the breadth func on wri ng the value is called mutator.
will set the breadth as zero. Next, we have
called the area func on. Then what will we Now few more things, for any data member
get? See length is 10 and breadth is 0 then the that is length or breadth, if you are wri ng both
area will be 0. By using the func on, we have get and set func on then the property is a read
created some condi ons that should be writeable. If you write only accessors or get
followed to assign values to data members. func ons and don’t write a set func on, then it
With this, we will not get any wrong results or is read-only. You cannot write the property you
nega ve results. But s ll, the main func on is cannot change the property so it depends on
not knowing or the user is not knowing that you, which property you want to be read
there is a problem with the nega ve value. So, writeable or only readable. Now let us write
if you want you can write “length or breadth the complete program.
cannot be nega ve” inside the setLength and
setBreadth func on. Next, we want to display Program to Understand Data Hiding in C++:
the length of a rectangle or breadth of a #include <iostream>
rectangle. So, we can say, using namespace std;
class Rectangle
r.getLength(); {
r.getBreadth(); private:
int length;
It will give the value of Length and Breadth and int breadth;
print on the screen. Finally, we have achieved
data hiding. We made the data private and public:
made the func ons public and because we void setLength (int l)
were unable to access the data, we have {
provided some valida ng func ons or if (l >= 0)
intelligence which will take the valid data and length = l;
assign it to those data members. If it is invalid else
then you can print a message that tells the user {
that the data is invalid. length = 0;
cout << "Length cannot be nega ve or
How many func ons we have wri en? zero" << endl;
The setLengh, setBreadth, getLength and }
getbreadth. We have wri en two data
func ons get and set. The ‘get’ will give you the }
value of data members and the ‘set’ will void setBreadth (int b)
change the value of the data members. So, {
if (b >= 0) Why do we need Constructors in C++?
breadth = b; Before understanding what are constructors,
else let’s first understand why we need
{ Constructors in C++. For a be er understanding
breadth = 0; please have a look at the below code.
cout << "Breadth cannot be nega ve or
zero" << endl;
} class Rectangle
{
} private:
int getLength () int length;
{ int breadth;
return length; public:
} void setLength (int l)
int getBreadth () {
{ if (l >= 0)
return breadth; length = l;
} else
int Area () length = 0;
{ }
return length * breadth; void setBreadth (int b)
} {
int Perimeter () if (b >= 0)
{ breadth = b;
return 2 * (length + breadth); else
} breadth = 0;
}; }
int main() int getLength ()
{ {
Rectangle r; return length;
r.setLength (10); }
r.setBreadth (10); int getBreadth ()
cout << "Area: " << r.Area () << endl; {
cout << "Perimeter: " << r.Perimeter () << return breadth;
endl; }
} int Area ()
Output: {
return length * breadth;
Constructors in C++ with Examples }
In this ar cle, I am going to discuss int Perimeter ()
Constructors in C++ with Examples. Please read {
our previous ar cle, where we discussed Data return 2 * (length + breadth);
Hiding in C++ with Examples. At the end of this }
ar cle, you will understand what are };
Constructors and their type as well as their role Here we have a class called Rectangle with
and responsibility in C++ Applica ons with length and breadth as data members as well as
Examples. the accessor and mutator methods for these
two data members. Now we will create an from the market and it has no color. When you
object class Rectangle. placed an order at that me only you said that
I want a white color car or any other color car.
Rectangle r; So, the color of this car is white. It is not like
first you will buy a car and bring it home and
The object of the Rectangle class is created then you give white color.
having length and breadth as shown in the
below image. Coming back to our example, first, we are
crea ng a rectangle object, and then only we
are se ng its length and breadth data
Why do we need Constructors in C++? members. This Philosophically is wrong. When
you booked the car, at that me only you said
Now, we can access all the func ons of class that the car color should be white and then you
Rectangle through object r. Now the problem is should get a white car. That’s it. So, when the
that we have created an object of Rectangle. car is delivered, it is having some color, not
We got length and breadth. But what are the garbage.
values stored in them? There are no values. Did
we ini alize them? No. So they have garbage
values. Then we want to set the length. So, we In the same way, when you are crea ng an
should call the setLength and setBreadth object of Rectangle at that me only, we should
func ons. We are calling these func ons which be able to say that I want the length of 10 and
will take the given value and set them to length a breadth of 5. You don’t have to set it up later.
and breadth data members. This So, this is the philosophy behind that one.
Philosophically is totally wrong. Let’s see how.
We want the length and breadth to be set at
We have created an object of Rectangle. Later the me of construc on of that object. So,
we set the length and breadth data members. what we should have inside the class? What is
There is a problem. What is that? Suppose we visible or publicly accessible? Func ons. So, we
have purchased a rectangle from the market. should have a func on that should
So, when we purchase it, was it not have any automa cally be called when an object is
length and breadth? When we buy something constructed. That func on will take values of
from the market or when we get something length and breadth as parameters and assign
constructed in some factory and when they those values. These func ons are known as
hand over the thing to us then that thing will Constructors in C++.
have some proper es. Suppose if it is a
rectangle then it must have some length and What are Constructors in C++?
breadth. How it can be garbage random length C++ allows the object to ini alize itself when it
and breadth? There must be some length and is created. This automa c ini aliza on of the
breadth, not just garbage. object is known as Constructors. The
constructor in C++ is a block of code that
ini alizes the newly created object.
Let’s understand the same concept with one
more example. Suppose we have a car and
color is the property of the car. A constructor ini alizes an object immediately
upon crea on. It has the same name as the
You have bought a car and the car will have class in which it resides and is syntac cally
some color. What is the color of the car? No similar to a method. Once defined, the
color. How it is possible that you bought a car constructor is called automa cally immediately
while crea ng the object. Constructors have no every class will have some constructor. If we
return type, not even void. don’t provide any constructor explicitly, then
the compiler provides a built-in constructor
So, in simple words, we can define the which is called as default constructor.
constructors in C++ are the special types of
methods of a class that are automa cally Types of Constructors in C++:
executed whenever we create an instance A constructor is a func on that will have the
(object) of that class. The Constructors are same name as the class name. Can we write
responsible for two things. One is the object our own constructor? Yes, we can write our
ini aliza on and the other one is memory own constructors. Then how we can write? We
alloca on. can write three different types of constructors.

Constructors Examples in C++:


Now, let us try to understand constructors with Non-Parameterized Constructor
some examples. Please have a look at the Parameterized Constructor
below class. The following is a class with the Copy Constructor
name Rectangle having two private data Types of Constructors in C++
members called length and breadth.
Note: If you don’t write any of them then a
default constructor is provided by the compiler.
class Rectangle { Some mes the non-parameterized constructor
private: is also called a default constructor and the
int length; default is called also called a built-in
int breadth; constructor. Now, let us understand all these
}; constructors through examples.
Now, let us create an object of the Rectangle
class as follows: Default Constructor in C#:
The Constructor without a parameter is called
Rectangle r; the default constructor in C++. Again, the
default constructor in C++ is classified into two
An object of Rectangle is created and it will be types. They are as follows.
shown in the memory as shown in the below
image.
System-Defined Default Constructor / Built-in
Constructor
Constructors Examples in C++ User-Defined Default Constructor
What is System Defined Default Constructor in
C#?
As you can see in the above image, this object If we are not defined any constructor explicitly
(r) is having length and breadth data members. in our class, then by default the compiler will
We can call it as the object is constructed. Who provide one constructor while genera ng the
constructed it? There is a func on that machine code. That constructor is called a
constructed it i.e. constructor. Did we write any default constructor. The default constructor
func on in the class? No. Then who wrote the will assign default values to the data members.
func on? The compiler will provide a func on As this constructor is created by the system this
for this when it converts the class code into is also called a system-defined default
machine code. That is not visible to us. That constructor.
constructor will create this object. That means
Example to Understand Default Constructor in The constructor which is defined by the user
C++: without any parameter is called a user-defined
In the below example, within the Rectangle default constructor in C++. This constructor
class, we have not defined any constructor does not accept any argument but as part of
explicitly. So, while genera ng the machine the constructor body, you can write your own
code, the compiler will provide the default logic. This is also called a non-parameterized
constructor. constructor as it does not take any parameter.
The following is the syntax.
#include <iostream>
using namespace std;
class Rectangle Rectangle()
{ {
private: length = 10;
int length; breadth = 20;
int breadth; }
public:
Example of User-Defined Default Constructor
void Display() in C++:
{ In the below example, we gave created the
cout << "Length: " << length << " Breadth: constructor without a parameter. This is called
" << breadth; a user-defined default constructor. As part of
} the constructor body, we have ini alized the
}; length and breadth data members with the
int main() values 10 and 20 respec vely. So, when we
{ created an object of the Rectangle class, this
Rectangle r; constructor will call automa cally and set the
r.Display(); length and breadth values 10 and 20.
}
Output: #include <iostream>
Examples to Understand Default Constructor in using namespace std;
C++ class Rectangle
{
private:
Note: The point that you need to remember is int length;
that the compiler will only provide the default int breadth;
constructor if as a programmer you are not public:
defined any constructor explicitly in our class. Rectangle ()
{
When do we need to provide the constructor length = 10;
explicitly in C++? breadth = 20;
If you want to execute some logic at the me }
of object crea on, that logic may be object void Display()
ini aliza on logic or some other useful logic, {
then as a developer, we should define the cout << "Length: " << length << " Breadth:
constructor explicitly in our class. " << breadth;
}
What is a User-Defined Default Constructor in };
C++? int main()
{ and breadth data members respec vely. Now,
Rectangle r; while crea ng the Rectangle object, we need to
r.Display(); provide the values for the l and b parameters
} of the constructor.
Output:
Example of User-Defined Default Constructor #include <iostream>
in C++ using namespace std;
class Rectangle
{
The drawback of the above user-defined private:
default constructor is that every instance (i.e. int length;
for every object) of the class will be ini alized int breadth;
(assigned) with the same values. That means it public:
is not possible to ini alize each instance of the Rectangle (int l, int b){
class with different values. length = l;
breadth = b;
When should we define a Parameterized }
Constructor in a Class? void Display()
If we want to ini alize the object dynamically {
with the user-given values then we need to use cout << "Length: " << length << " Breadth:
the parameterized constructor in C++. The " << breadth;
advantage is that we can ini alize each object }
with different values. };
int main()
What is Parameterized Constructor in C++? {
The user-given constructor with parameters is Rectangle r1(10, 20);
called the parameterized constructor in C++. r1.Display();
With the help of a Parameterized constructor, cout << endl;
we can ini alize each instance of the class with Rectangle r2(30, 40);
different values. That means using r1.Display();
parameterized constructor we can store a }
different set of values in different objects Output:
created in the class. Following is the syntax. Example to understand the Parameterized
Constructor in C++
Rectangle (int l, int b){
length = l;
breadth = b; How many constructors can be defined in a
} class in C++?
The following is the syntax to create the In C++, in a class, we can define one no-
Rectangle object. argument constructor plus “n” number of
Rectangle r1(10, 20); parameterized constructors. But the most
Rectangle r2(30, 40); important point that you need to remember is
that each and every constructor must have a
Example to understand the Parameterized different signature. A different signature
Constructor in C++: means the number, type, and parameter order
In the below example, we have created the should be different.
constructor which takes two integer
parameters and then sets the values of length What is Copy Constructor in C++?
The constructor which takes a parameter of the int length;
class type is called a copy constructor. This int breadth;
constructor is used to copy one object’s data public:
into another object. The main purpose of the Rectangle (int l, int b){
copy constructor is to ini alize a new object length = l;
(instance) with the values of an exis ng object breadth = b;
(instance). The following is the syntax to create }
a Copy Constructor in C++
Rectangle(Rectangle &rect){
Rectangle(Rectangle &rect){ length = rect.length;
length = rect.length; breadth = rect.breadth;
breadth = rect.breadth; }
} void Display()
{
cout << "Length: " << length << " Breadth:
This is a copy constructor. Here, usually, we " << breadth;
take objects by reference and not by value. So }
that when we are calling a constructor, a new };
rectangle object should not be created. So int main()
that’s why we take it as a reference. Then inside {
the constructor, we assign length and breadth Rectangle r1(10, 20);
to the length and breadth of the rect object. r1.Display();
Following is the syntax to call the Copy cout << endl;
Constructor in C++. Rectangle r2(r1);
r2.Display();
Rectangle r2(r1); }
Output:
We have sent the r1 object as a parameter and Example to understand the Copy Constructor in
this will create another rectangle object that is C++
r2. So r will become “rect” here.
What is the Philosophy Behind the
Constructor?
Example to understand the Copy Constructor in Now I will explain to you what is the philosophy
C++ behind the constructor. Let us understand
In the below example, we have created two where we use non-parameterized,
constructors. One is the parameterized parameterized, and copy constructors.
constructor which takes two integer
parameters. The second one is also a
parameterized constructor which takes the Suppose you have placed an order for
class reference as a parameter as it takes the manufacturing a car or o en we directly go to
class reference is a parameter, so it is also the market and buy the items. That item was
called a copy constructor. also manufactured already. They will keep it
ready-made. Just go and buy whatever you
#include <iostream> want.
using namespace std;
class Rectangle Now let us take another example. Suppose you
{ have gone to a shop to buy a marker. Now,
private: what are the op ons you have to buy a marker?
First, you go to a shop and say “give me a The third is if any person has ‘x’ type of pizza
marker”. You did not specify a brand name and then I will say that I want that ‘x’ type of pizza
a color for the marker. You did not men on that is a copy of ‘x’.
anything just said I want a marker. Points to Remember while working with
Constructors in C++:
When you said just, I want a marker, whatever A constructor is a member func on of a class
the frequently sold marker is there in the It will have the same name as the class name
market or in the shop, he will simply hand over It will not have a return type
that marker to you. When you said just pen, so It should be public
commonly use the blue color pen of commonly It can be declared private also in some cases
running brand. So, you will get that pen. So, you It is called when the object is created
did not give the color or brand so we can say it It is used for ini alizing an object
is non-parameterized. This is the first method. It can be overloaded
If it is not defined then the class will have a
default constructor
I have a rectangle. Ini ally, length and breadth Constructors can take default arguments
are 0 later we can change it but ini ally, there Types of Constructors:
should be something. It cannot be garbage. Non-argument constructor
Then the second method is when you go to a Parameterized constructor
shop and say “I want a red color marker of Copy constructor
“xyz” brand”. So, you are men oning some All types of Member Func ons:
details here and he will give you that marker Constructors – called when the object is
only. So, you have given the parameters. We created
can say it is parameterized. Accessors – used for knowing the value of data
members
We want a rectangle of length should be 10 and Mutators – used for changing the value of data
a breadth should be 5. The third method is member
when you went to a shop and you are showing Facilitator – actual func ons of class
him a marker and you want a marker like you Enquiry – used for checking if an object
to have or copy of that one. So, he will give a sa sfies some condi on
new marker for you that is a copy of the marker Destructor – used for releasing resources used
that you already have. by the object
So, this is the purpose of the constructor and
Now we can understand there are three usage of the constructor. Now let us write the
methods of buying things from a market. complete program for constructors

Example to Understand Constructors in C++:


The first one is just going out and saying I want #include <iostream>
this. He will give you. If you go to a restaurant using namespace std;
or food store and say “I want pizza”. If the seller class Rectangle
has only one category of pizza or commonly {
people take the same type of pizza, they will private:
hand it over to you. int length;
Second, if I want a par cular type of pizza like int breadth;
cheese, tomato, Sause, and so on then this is public:
known as parameterized as I am specifying the Rectangle (int l = 0, int b = 0)
pizza type. {
setLength (l);
setBreadth (b); Output:
} Example to Understand Constructors in C++
Rectangle (Rectangle & rect)
{ How constructors are different from a normal
length = rect.length; member func on?
breadth = rect.breadth; A constructor is different from normal
} func ons in the following ways:
void setLength (int l)
{
if (l >= 0) The Constructor has the same name as the
length = l; class name itself.
else Default Constructors don’t have input
length = 0; arguments however, Copy and Parameterized
} Constructors can have input arguments
void setBreadth (int b) A Constructor should not have a return type,
{ even not void.
if (b >= 0) The constructor will automa cally call when an
breadth = b; object is created.
else It must be placed in the public sec on of the
breadth = 0; class.
} If we do not specify a constructor, the C++
int getLength () compiler generates a default constructor for
{ the object.
return length; Difference Between Func ons and
} Constructors in C++
int getBreadth () Constructors
{ It is a special type of func on used to ini alize
return breadth; objects of their class.
} The purpose of a constructor is to create an
}; object of a class.
int main() Constructor is called automa cally when we
{ are crea ng an object.
Rectangle r; They are used to ini alize objects that don’t
Rectangle r1 (3); exist.
Rectangle r2 (4, 7); The name of the constructor should be the
cout << "r:" << endl; same as the class name of the class.
cout << "Length: " << r.getLength () << " They are not inherited by subclasses.
Breadth: " << r. Func ons:
getBreadth () << endl; Func ons are a set of instruc ons that are
cout << "r1:" << endl; invoked at any point in a program to perform a
cout << "Length: " << r1.getLength () << " specific task.
Breadth: " << r1. The purpose of a func on is to execute C++
getBreadth () << endl; code to perform a specific task.
cout << "r2:" << endl; We need to call explicitly a func on to execute.
cout << "Length: " << r2.getLength () << " They perform opera ons on already created
Breadth: " << r2. objects.
getBreadth () << endl; We can give any valid name to func ons in C++.
} They are inherited by subclasses.

You might also like