5 - Encapsulation, Abstraction, Polymorphism
5 - Encapsulation, Abstraction, Polymorphism
ENCAPSULATION, ABSTRACTION,
COURSE NAME POLYMORPHISM
INTRODUCTION TO
PROGRAMMING
CSC 1102
MD.NAZMUL HOSSAIN
(UNDERGRADUATE) LECTURER, CS, AIUB
Data Abstraction Slide-2
MMH
Slide-4
#include <iostream> Example of Data Abstraction
using namespace std;
class Adder{
public:
Data Encapsulation prevents users
int main( ) of the classes from unintentionally
// interface to outside world { altering a critical piece of data or
void addNum(int number) { Adder a; gaining access to a sensitive data
total += number;
a.addNum(10); item. This programming strategy is
}
a.addNum(20); called encapsulation or data hiding
// interface to outside world a.addNum(30);
int getTotal() {
cout << "Total “
return total;
}; << a.getTotal();
private: return 0;
// hidden data from outside world }
int total = 2; Output
}; Total 62
MMH
Slide-5
Abstract Class (Interface)
An interface describes the behavior or capabilities of a C++ class without committing
to an implementation of that class.
The C++ interfaces are implemented using abstract classes and these abstract
classes should not be confused with data abstraction which is a concept of keeping
implementation details separate from associated data.
class Box
{
A class is made abstract by public:
declaring at least one of its virtual double getVolume() = 0; // pure virtual
functions as pure virtual function
MMH
Slide-7
Polymorphism
The word polymorphism means having many forms.
Typically, polymorphism occurs when there is a hierarchy of classes and they are
related by inheritance.
C++ polymorphism means that a call to a member function will cause a different
function to be executed depending on the type of object that invokes the function.
Function Overloading is also called Compile time Polymorphism
MMH
Slide-10
#include <iostream>
using namespace std; Polymorphism (run-time)
class Shape { class Rectangle: public Shape{
protected:
int width, height; public:
MMH
Slide - 20
REFERENCES