Unit-2: Classes and objects

Encapsulation

Encapsulation is a process of combining data members and functions in a single unit called class. This is to prevent the access to the data directly, the access to them is provided through the functions of the class. It is one of the popular feature of Object Oriented Programming(OOPs) that helps in data hiding.

How Encapsulation is achieved in a class

To do this:
1) Make all the data members private.
2) Create public setter and getter functions for each data member in such a way that the set function set the value of data member and get function get the value of data member.

Let’s see this in an example Program:

Encapsulation Example in C++

Here we have two data members num and ch, we have declared them as private so that they are not accessible outside the class, this way we are hiding the data. The only way to get and set the values of these data members is through the public getter and setter functions.

#include<iostream>
using namespace std;
class ExampleEncap{
private:
   int num;
   char ch;
public:
   int getNum() const {
      return num;
   }
   char getCh() const {
      return ch;
   }
 
  void setNum(int num) {
      this->num = num;
   }
   void setCh(char ch) {
      this->ch = ch;
   }
};
int main(){
   ExampleEncap obj;
   obj.setNum(100);
   obj.setCh('A');
   cout<<obj.getNum()<<endl;
   cout<<obj.getCh()<<endl;
   return 0;
}

Output:

100
A

information hiding

Information hiding or data hiding in programming is about protecting data or information from any inadvertent change throughout the program. Information hiding is a powerful OOP feature. Information hiding is closely associated with encapsulation.

Information hiding definition Information or data hiding is a programming concept which protects the data from direct modification by other parts of the program.

The feature of information hiding is applied using Class in most of the programming languages.

example of information hiding in C++:


class student
{
char name[30];
int marks;
public:
void display();
};

int main()
{
student S;
S.marks=50; // Wrong code!
getch();
return 0;
}

The accessibility often plays an important role in information hiding. Here the data element marks is private element and thus it cannot be accessed by main function or any other function except the member function display() of class student. To make it accessible in main function, it should be made a public member.

Key Differences Between Data Hiding and Encapsulation

  1. Encapsulation deals with hiding the complexity of a program. On the other hand, data hiding deals with the security of data in a program.
  2. Encapsulation focuses on wrapping (encapsulating) the complex data in order to present a simpler view for the user. On the other hand, data hiding focuses on restricting the use of data, intending to assure the data security.
  3. In encapsulation data can be public or private but, in data hiding, data must be private only.
  4. Data hiding is a process as well as a technique whereas, encapsulation is subprocess in data hiding.

abstract data types

An abstract data type (or ADT) is a class that has a defined set of operations and values. In other words, you can create the starter motor as an entire abstract data type, protecting all of the inner code from the user. When the user wants to start the car, they can just execute the start() function.

 In programming, an ADT has the following features:

  • An ADT doesn’t state how data is organized, and
  • It provides only what’s needed to execute its operations

An ADT is a prime example of how you can make full use of data abstraction and data hiding. This means that an abstract data type is a huge component of object-oriented programming methodologies: enforcing abstraction, allowing data hiding (protecting information from other parts of the program), and encapsulation (combining elements into a single unit, such as a class).

object and classes

OBJECT– In object-oriented programming languages like C++, the data and functions (procedures to manipulate the data) are bundled together as a self-contained unit called an object . 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

Class: The building block of C++ that leads to Object Oriented programming is a 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 brand but all of them will share some common properties like all of them will have 4 wheelsSpeed LimitMileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.

  • A Class is a user defined data-type which has data members and member functions.
  • Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions defines the properties and behavior of the objects in a Class.
  • In the above example of class Car, the data member will be speed limitmileage etc and member functions can be apply brakesincrease speed etc.
  • A class is an abstract data type similar to ‘C structure‘.
  • The Class representation of objects and the sets of operations that can be applied to such objects.
  • The class consists of Data members and methods.

The primary purpose of a class is to hold data/information. This is achieved with attributes which are also known as data members.

The member functions determine the behavior of the class i.e. provide a definition for supporting various operations on data held in form of an object.

Definition /declaration of a class

Syntax:

Class class_name
{
    Data Members;
    Methods;
}

Example:

class A
{
    public:
    double length; // Length of a box
    double breadth; // Breadth of a box
    double height; // Height of a box 
}
  • PrivateProtectedPublic is called visibility labels.
  • The members that are declared private can be accessed only from within the class.
  • Public members can be accessed from outside the class also.
  • In C++, data can be hidden by making it private.

class members

Data and functions are members.

Data Members and methods must be declared within the class definition.Example:

Class A
{
    int i; // i is a data member of class A
    int j; // j is a data member of class A
    int i; // Error redefinition of i 
}
  • A member cannot be redeclared within a class.
  • No member can be added elsewhere other than in the class definition.

Example:

Class A
{
    int i;
    int j;
    void f (int, int);
    int g(); 
}

f and g are a member function of class A. They determine the behavior of the objects of class A.

Accessing the Data Members

The public data members are also accessed in the same way given however the private data members are not allowed to be accessed directly by the object. Accessing a data member depends solely on the access control of that data member.
This access control is given by Access modifiers in C++. There are three access modifiers : public, private and protected.

state,identity,behaviour of an object

State: Represents data (value) of an object.

Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.

Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But,it is used internally by the JVM to identify each object uniquely.

Constructor in C++

Constructor is a special member method which will be called implicitly (automatically) whenever an object of class is created. In other words, it is a member function which initializes a class which is called automatically whenever a new instance of a class is created.

Features of Constructor

  • The same name as the class itself.
  • no return type.

Syntax

classname()
{
....
}

Note: If you do not specify a constructor, the compiler generates a default constructor for you (expects no parameters and has an empty body).

Why use constructor ?

The main use of constructor is placing user defined values in place of default values.

How Constructor eliminate default values ?

Constructor are mainly used for eliminate default values by user defined values, whenever we create an object of any class then its allocate memory for all the data members and initialize there default values. To eliminate these default values by user defined values we use constructor.

Example of Constructor in C++

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

class sum
{
int a,b,c;
sum()
{
a=10;
b=20;
c=a+b;
cout<<"Sum: "<<c;
}
};

void main()
{
sum s;
getch();
}

Output

Sum: 30

In above example when we create an object of “Sum” class then constructor of this class call and initialize user defined value in a=10 and b=20. And here we no need to call sum() constructor.

Destructor

Destructor is a member function which deletes an object. A destructor function is called automatically when the object goes out of scope:

When destructor call

  • when program ends
  • when a block containing temporary variables ends
  • when a delete operator is called

Features of destructor

  • The same name as the class but is preceded by a tilde (~)
  • no arguments and return no values

Syntax

~classname()
{
......
}

Note: If you do not specify a destructor, the compiler generates a default destructor for you.

Example of Destructor in C++

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

class sum
{
int a,b,c;
sum()
{
a=10;
b=20;
c=a+b;
cout<<"Sum: "<<c;
}
~sum()
{
cout<<<<endl;"call destructor";
}
delay(500);
};

void main()
{
sum s;
cout<<<<endl;"call main";
getch();
}

Output

Sum: 30
call main
call destructor

Explanation: In above example when you create object of class sum auto constructor of class is call and after that control goes inside main and finally before end of program destructor is call.