Object-Oriented Programming Concepts Abstraction and Encapsulation 1 Objectives • Understand Abstraction and Encapsulation • Understand Constructors and Destructors • Create constructors and destructors Definitions: • Abstraction: Act of Representing essential features without including the background details or explanations. • Encapsulation: wrapping up of data and functions (methods) into a single unit called class. Recall…..Access Modifiers • In our previous lecture, we sais there are 3 types of access modifiers available in C++ namely: 1. Public 2. Private 3. Protected • Access modifiers are used to implement an important feature of Object-Oriented Programming known as Data Hiding. • Access Modifiers or Access Specifiers in a class are used to set the accessibility of the class members. – It sets some restrictions on the class members not to get directly accessed by the outside functions. Encapsulation and Data Hiding • Encapsulation is a programming mechanism that binds (wraps) together code and the data it manipulates, and that keeps both safe from outside interference and misuse. • C++’s basic unit of encapsulation is the class: – Within a class, code or data or both may be private to that object or public or protected. – Private code or data is accessible by only another part of the object and cannot be accessed by a piece of the program that exists outside the object. – Public code or data is accessible to other parts of your program – Typically, the public parts of an object are used to provide a controlled interface to the private elements of the object. Encapsulation Syntax of Encapsulation in C++ class class name { private: datatype data; public: Member functions; }; main() { classname objectname1,objectname2……………; } Encapsulation - real life example In a company there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keep records of all the data related to finance. Similarly the sales section handles all the sales related activities and keep records of all the sales. Now there may arise a situation when for some reason an official from finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of sales section and the employees that can manipulate them are wrapped under a single name “sales section”. Encapsulation and Data Hiding • This insulation of the data from direct access by the program is called data hiding. • Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. • Consider the following examples… Example 1 // c++ program to explain Encapsulation #include<iostream> using namespace std; class Encapsulation { private: // data hidden from outside world int x; public: // function to set value of variable x void set(int a) { x =a; } // function to return value of variable x int get() { return x; } }; // main function int main() { Encapsulation obj; obj.set(5); cout<<obj.get(); return 0; } • • In this program the variable x is made private, it can be accessed and manipulated only using the functions get() and set() which are present inside the class. We can therefore say that, variable x and the functions get() and set() are binded together which is nothing but encapsulation. Example 2 #include <iostream> using namespace std; class Adder { public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; int main() { //create an object called a of class Adder Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total " << a.getTotal() <<endl; return 0; } output • • In this program, the public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is hidden from the outside world, but is needed for the class to operate properly. Role of Access Specifiers In Encapsulation • As shown in previous example, access specifiers plays an important role in implementing encapsulation in C++. • The process of implementing encapsulation can be sub-divided into two steps: – The data members should be labeled as private using the private access specifiers – The member function which manipulates the data members should be labeled as public using the public access specifier Abstraction • Encapsulation also lead to data abstraction or hiding. – As using encapsulation also hides the data. – In the previous example the data of any of the section like sales, finance or accounts is hidden from any other section. • Abstraction is therefore the technique of hiding internal details in an object. – The act of representing essential features without including the background details or explanations. • In C++ encapsulation can be implemented using Class and access modifiers. 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 and they are not allowed to be accessed from any part of code outside the class. Abstraction using access specifiers • To implement abstraction using the above two features (private and public provided by access specifiers: 1. the members that defines the internal implementation can be marked as private in a class. 2. the important information needed to be given to the outside world can be marked as public. • Public members can access the private members as they are inside the class. • See example next slide… #include <iostream> using namespace std; class implementAbstraction { private: int a, b; public: // method to set values of private members void set(int x, int y) { a = x; b = y; } void display() { cout<<"a = " <<a << endl; cout<<"b = " << b << endl; } }; // main function int main() { implementAbstraction obj; obj.set(10, 20); obj.display(); return 0; } • In this 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. Constructors in C++ • Constructor is a special member function of a class that initializes the object of the class. • Constructor name is same as class name and it doesn’t have a return type. • In simple words a constructor:1. Is a special type of method used to initialize the class members. 2. Has the same name as the class itself. 3. Does not specify return type nor void because they return the instance of the class itself. Types of Constructors • There are two types of constructor in C++ 1. Default constructor 2. Parameterized constructor Default Constructor • A default constructor doesn’t have any arguments (or parameters) Parameterized Constructor • Constructors with parameters are known as Parameterized constructors. • These type of constructor allows us to pass arguments while object creation. Example 1 – using Default constructor #include <iostream> using namespace std; class construct { public: int a, b; // Default Constructor construct() { a = 10; b = 20; } }; int main() { // Default constructor called automatically // when the object is created construct c; cout << "a: " << c.a << endl << "b: " << c.b; return 1; } Example 2 – using Parametarized constructor #include <iostream> using namespace std; class Point { private: int x, y; public: // Parameterized Constructor Point(int x1, int y1) { x = x1; 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(); cout << ", p1.y = " << p1.getY(); return 0; } When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly Example 3 – using Parametarized constructor #include <iostream> using namespace std; class Add { public: //Parameterized constructor Add(int num1, int num2) { cout<<(num1+num2)<<endl; } }; int main(void) { // This is one way of creating object, also known as implicit call to the constructor Add obj1(10, 20); //Another way of creating object, this is known as explicit calling the constructor Add obj2 = Add(50, 60); return 0; } Constructor vs Member Function 1. Constructor doesn’t have a return type 1. Member function has a return type. 2. Constructor is automatically called when we create the object of the class 2. Member function needs to be called explicitly using object of class. 3. When we do not create any constructor in our class, C++ compiler generates a default constructor and insert it into our code. 3. The same does not apply to member functions – C++ compiler does not generate a default member function Destructors in C++ • A Destructor is a special member function destroys (or deletes or destructs ) an object. • Destructor works just opposite to constructor. Syntax of Destructor ~class_name() { //Some code } that Destructors in C++ In creating a destructor, the following rules are followed: 1. The name of a destructor should begin with tilde sign(~) and must match class name. 2. There cannot be more than one destructor in a class. 3. Unlike constructors that can have parameters, destructors do not allow any parameter. 4. Destructors do not have any return type, just like constructors. 5. The compiler generates a default destructor and inserts it into your code in the event a destructor is not specified in a class. Example 1 – Destructor #include <iostream> using namespace std; class HelloWorld { public: //Constructor HelloWorld() { cout<<"Constructor is called"<<endl; } //Destructor ~HelloWorld() { cout<<"Destructor is called"<<endl; } //Member function void display() { cout<<"Hello World!"<<endl; } }; int main() { //Object created HelloWorld obj; //Member function called obj.display(); return 0; } Example 2 – Constructor and Destructor #include <iostream> using namespace std; class Rectangle { int length; int breadth; public: void setDimension(int l, int b) { length = l; breadth = b; } int getArea() { return length * breadth; } // Constructor Rectangle() { cout << "Constructor" << endl; } // Destructor ~Rectangle() { cout << "Destructor" << endl; } }; int main() { Rectangle rt; rt.setDimension(7, 4); cout << rt.getArea() << endl; return 0; } • • • In this program, when the object 'rt' of class Rectangle is created, the constructor is called, no matter whichever order we define it in the class. After that, the object calls the functions ‘setDimension(7, 4)' and 'getArea()' and prints the area. Finally, when the object gets out of scope, its destructor is called. References 1. 2. 3. 4. 5. https://www.tutorialspoint.com/cplusplus/index.htm https://www.javatpoint.com/cpp-object-and-class https://www.geeksforgeeks.org/encapsulation-in-c/ https://www.sitesbay.com/cpp/cpp-encapsulation https://beginnersbook.com/2017/08/cpp-constructors/