0% found this document useful (0 votes)
3 views51 pages

OOP Lecture 3

This document covers encapsulation in Object-Oriented Programming (OOP), particularly in C++. It explains the concept of encapsulation, its properties, features, and the role of constructors, including types such as default, parameterized, copy, and move constructors. Additionally, it highlights the differences between abstraction and encapsulation, and the importance of access specifiers and the 'this' keyword in managing object data and methods.

Uploaded by

processingwait
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views51 pages

OOP Lecture 3

This document covers encapsulation in Object-Oriented Programming (OOP), particularly in C++. It explains the concept of encapsulation, its properties, features, and the role of constructors, including types such as default, parameterized, copy, and move constructors. Additionally, it highlights the differences between abstraction and encapsulation, and the importance of access specifiers and the 'this' keyword in managing object data and methods.

Uploaded by

processingwait
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

OBJECT ORIENTED PROGRAMMING

[CS1420]

L E C T U R E 3 : I N F O R M AT I O N H I D I N G U S I N G
E N C A P S U L AT I O N
Constructors, Encapsulation, Information Hiding, Access
Specifiers, Properties (getter Setter)

Engr. Syeda Aimen Naeem


[email protected]
ENCAPSULATION
• Encapsulation in C++ is defined as the wrapping up of data and information in a single unit.
• In Object Oriented Programming, Encapsulation is defined as binding together the data and the
functions that manipulate them.

• The process of implementing encapsulation can be sub-divided into two steps:


• Creating a class to encapsulate all the data and methods into a single unit.
• Hiding relevant data using access specifiers.
ENCAPSULATION EXAMPLE
• there are different sections like the accounts section, finance section, sales section, etc.
• The finance section handles all the financial transactions and keeps records of all the data
related to finance.
• Similarly, the sales section handles all the sales-related activities and keeps records of all
the sales.
• when for some reason an official from the finance section needs all the data about sales in a
particular month. He is not allowed to directly access the data of the sales section. He will first
have to contact some other officer in the sales section and then request him to give the particular
data.
• data of the sales section and the employees that can manipulate them are wrapped under a single
name “sales section”.
PROPERTY OF ENCAPSULATION
1.Data Protection: Encapsulation protects the internal state of an object by
keeping its data members private. Access to and modification of these data
members is restricted to the class’s public methods, ensuring controlled and
secure data manipulation.
2.Information Hiding: Encapsulation hides the internal implementation details of
a class from external code. Only the public interface of the class is accessible,
providing abstraction and simplifying the usage of the class while allowing the
internal implementation to be modified without impacting external code.
FEATURES OF ENCAPSULATION
1. We can not 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 member variables, only then
it is called encapsulation.
3. If we don’t make a function inside the class which is using the at least one member
variable of the class then we don’t call it encapsulation.
4. Encapsulation improves readability, maintainability, and security by grouping data and
methods together.
5. It helps to control the modification of our data members.
IMPLEMENTATION THROUGH
PROPERTIES
• In encapsulation, properties refer to a mechanism that allows controlled access
to private data members while maintaining data hiding and integrity.
• Properties are commonly used in languages like C# and Python, but C++ does
not have built-in properties. Instead, getter and setter methods serve the same
purpose.
• Encapsulation can be implemented using
• Getter / Setter methods
• Constructors
GETTER / SETTER METHODS
• Getters: These are the methods used in Object-Oriented Programming (OOPS) which
helps to access the private attributes from a class.
int getSalary() {
return salary;
}

• Setters: These are the methods used in OOPS feature which helps to set the value to
private attributes in a class.
void setSalary(int s) {
salary = s;
}
EXAMPLE OF C++
class Person { void setAge(int age) { cout << "Name: " <<
private: this->age = age;} person.getName() << endl;

string name; int getAge() { cout << "Age: " << person.getAge()
<< endl;
int age; return age;}};
return 0;}
public:
void setName(string name) { int main() {
this->name = name;} Person person;
string getName() { person.setName("Jane Doe");

return name;} person.setAge(32);


#include <iostream> cout << "Enter radius\n";
using namespace std; cin >> radius; int main(){
class Circle { } Circle cir;
private: void findArea(){ cir.getRadius(); // calling
float area; area = 3.14 * radius * radius; function
float radius; cout << "Area of circle=" << cir.findArea(); // calling
area; function
public:
} }
void getRadius(){
};
EXAMPLE:
• Scenario: Bank Account System
• A bank does not allow direct modification of an account balance by users.
• Instead, it provides controlled access via functions like deposit() and withdraw(), which ensure
that:
• The balance cannot be negative.
• Only valid transactions are permitted.
ENCAPSULATION EXAMPLE
• A real-life example of encapsulation is a bank ATM
• Private Data (Encapsulated Information)
• Your account balance, PIN, and transaction history are hidden from direct access. You cannot
modify your account balance directly; you must go through secure functions like withdrawal or deposit.
• Public Interface (Controlled Access)
• The ATM provides specific options: withdraw money, check balance, deposit cash, etc. You cannot
access the internal working of the bank's database; you only interact with the ATM's functions.
• Security & Data Protection
• Your account details are not exposed to the user or external systems directly. The ATM ensures that only
authenticated users (with a valid card and PIN) can access their account.
DIFFERENCE B/W ABSTRACTION AND
ENCAPSULATION
Abstraction
• In OOPs, Abstraction is the method of getting information where the information needed will be
taken in such a simplest way that solely the required components are extracted, and also the ones
that are considered less significant are unnoticed. The concept of abstraction only shows
necessary information to the users. It reduces the complexity of the program by hiding the
implementation complexities of programs.
DIFFERENCE B/W ABSTRACTION AND
ENCAPSULATION
Encapsulation
• Encapsulation is the process or method to contain the information. Encapsulation is a method to
hide the data in a single entity or unit along with a method to protect information from outside
world. This method encapsulates the data and function together inside a class which also results
in data abstraction. .
DIFF. B/W ABSTRACTION & ENCAPSULATION
S.NO Abstraction Encapsulation

In abstraction, problems are solved at the design or While in encapsulation, problems are solved at the
1.
interface level. implementation level.

Whereas encapsulation is a method to hide the data in a single


Abstraction is the method of hiding the unwanted
2. entity or unit along with a method to protect information from
information.
outside.

Simplifies complexity by exposing only essential Protects data by restricting direct access and enforcing controlled
3. details while hiding internal workings. access via methods.

We can implement abstraction using abstract class Whereas encapsulation can be implemented using by access
4.
and interfaces. modifier i.e. private, protected and public.

In abstraction, implementation complexities are While in encapsulation, the data is hidden using methods of
5.
hidden using abstract classes and interfaces. getters and setters.

The objects that help to perform abstraction are Whereas the objects that result in encapsulation need not be
6.
encapsulated. abstracted.
CONSTRUCTORS
• Constructor is a member function of a class, whose name is same as the class
name.
• Constructor is a special type of member function that is used to initialize the data
members for an object of a class automatically, when an object of the same class
is created.
• Constructor is invoked at the time of object creation.
• The only restriction that applies to the constructor is that it must not have a
return type or void. It is because the constructor is automatically called by the
compiler and it is normally used to INITIALIZE VALUES.
CONSTRUCTOR
Syntax of Constructor
class CLASSNAME{
public :
CLASSNAME() // constructor definition
{
......
}
........
};
CONSTRUCTOR EXAMPLE
class Car { main() {
public:
string brand; Car carObj1("BMW", "X5", 1999);
string model; Car carObj2("Ford", "Mustang", 1969);
int year;
cout << carObj1.brand << carObj1.model <<
Car(string x, string y, int z) {
brand = x; carObj1.year << "\n";
model = y;
year = z; cout << carObj2.brand << carObj2.model <<
} carObj2.year << "\n";
}; return 0;
int }
TYPES OF CONSTRUCTORS

Default Class_name()

Parameteri
Class_name(parameters)
zed
Constructor
s
Class_name(const class_name
Copy
old_object)

Move className (className&& obj)


DEFAULT CONSTRUCTOR
• A default constructor is a constructor that doesn’t take any argument.
• It has no parameters. It is also called a zero-argument constructor.
• The compiler automatically creates an implicit default constructor if the
programmer does not define one.
DEFAULT CONSTRUCTOR
class creature };
{ int main()
private: {
int yearofBirth; creature obj; getch(); return 0;
public: }

creature(){
cout<<“Contructor called";
}
PARAMETERIZED CONSTRUCTORS:
◻A parameterized constructor is just one that has parameters specified in
it.
◻We can pass the arguments to constructor function when object are
created.

◻ A constructor that can take arguments are called parameterized


constructors.
EXAMPLE
class Creature {
private: int main(){
int yearOfBirth; Creature c(2001);
public:
}
// …
Creature(int year) {
yearOfBirth =year;
}
};

LECTURE 4
C O P Y CONSTRUCTOR
◻A copy constructor is a member function that initializes an object using another object of the
same class.
◻Copy constructor takes a reference to an object of the same class as an argument.
◻For example the statement:
• abc c2(c1);
• would define the object c2 and at the same time initialize it to
the value ofc1.
◻The process of initializing through a copy constructor is known as copy initialization.
EXAMPLE
class A { int main() {
public: A a1;
int x; a1.x = 10;
// Copy Constructor definition cout << "a1's x = " << a1.x << endl;
A (A& t) {
x = t.x; A a2(a1);
cout << "Calling copy constructor" << endl; cout << "a2's x = " << a2.x;
}}; return 0;}
MOVE CONSTRUCTOR
• The move constructor is a recent addition to the family of constructors in C++.
• It is like a copy constructor that constructs the object from the already existing objects., but
instead of copying the object in the new memory, it makes use of move semantics to transfer the
ownership of the already created object to the new object without creating extra copies.
• It can be seen as stealing the resources from other objects.

className (className&& obj) {


// body of the constructor
}
ACCESS SPECIFIER AND CONSTRUCTOR
• Constructors can be defined as public, protected, or private as per the
requirements
• By default or default constructors, which are created by the compiler are declared
as the public
• If the constructor is created as private, then we are not able to create its object.
• When there is no requirement of the object of a class (in a situation when all class
members are static) we can define its constructor as private.
ACCESS SPECIFIER AND CONSTRUCTOR
• Private constructors are useful when want to restrict the direct instantiation. (Ex: in singleton pattern
or factory method)
class Product {
private:
Product() {} // Private constructor
public:
static Product createProduct() {
return Product();
}};
“THIS” KEYWORD
• In C++, ‘this’ pointers is a pointer to the current instance of a class. It is used to refer to the object
within its own member functions.
• To understand ‘this’ pointer, it is important to know how objects look at functions and data
members of a class.
• Each object gets its own copy of the data member.
• All-access the same function definition as present in the code segment.
• The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is
available as a local variable within the body of all nonstatic functions.
“THIS” KEYWORD
class Test{ int main()
private: {
int x; Test obj;
public: int x = 20;
void setX (int x){ obj.setX(x);
this->x = x;} obj.print();
void print() { cout << "x = " << x << endl; } return 0;
}; }
CONSTRUCTOR OVERLOADING
• Constructor overloading in C++ is a feature that allows a class to have multiple constructors with
different parameter lists. Each constructor can have a different number or type of parameters,
enabling objects of the class to be initialized in various ways depending on the provided
arguments.
CONSTRUCTOR OVERLOADING
class Student { Student(string n, int a) { int main() {
public: name = n; Student student1;
Student() { age = a;} Student student2("Anya");
name = "Unknown"; void displayInfo() { Student student3("Harsh", 20);
age = 0;} cout << "Name: " << name student1.displayInfo();

Student(string n) { << ", Age: " << age << endl;} student2.displayInfo();
student3.displayInfo();
name = n;
age = 0;} private: return 0;}
string name;
int age;};
CHARACTERISTICS OF CONSTRUCTORS
• The name of the constructor is the same as its class name.
• Constructors are mostly declared as public member of the class though they can be declared as
private.
• Constructors do not return values, hence they do not have a return type.
• A constructor gets called automatically when we create the object of the class.
• Multiple constructors can be declared in a single class (it is even recommended – Rule Of Three,
The Rule of Five).
• In case of multiple constructors, the one with matching function signature will be called.
EXAMPLE
class abc{ void showdata(){
cout <<a <<" " <<b <<endl;}
Private:
};
int a, b;
public: int main(){
abc(int x, int y){
abc c1(10, 20);
a =x;
abc c2(c1);
b =y;}
c1.showdata();
abc(abc &p){ c2.showdata();
a = p.a; return 0;
b =p.b;} }
CONSTRUCTOR AND ENCAPSULATION
• Constructors play a key role in enforcing encapsulation by ensuring proper initialization of private data
members.
• Constructors support encapsulation by providing Data hiding, Automatic Initialization, Preventing
Uninitialized Data, and enforce rules on object creation
class BankAccount { balance = (initialBalance >= 0) ? initialBalance : 0;}
private:
void display() {
string accountHolder;
cout << "Account Holder: " << accountHolder ;
double balance;
cout << "Balance: $" << balance << endl; }};
public:
BankAccount(string name, double initialBalance) {

accountHolder = name;
CONSTRUCTOR CALL IN INHERITANCE
• When the Object of child class created the constructor of child class either
implicitly or explicitly called the base class constructor and when the base class
constructor is called, base class members are also created and Initialized.
• This is the reason using the derived class object we can access both base class
and derived class members.
ORDER OF CONSTRUCTOR CALL FOR
INHERITANCE
• A parent class object only calls the parents class constructor
• Child class object implicitly calls parent class default constructor first before
calling its own constructor
• Compiler implicitly create default constructors only when there is no constructor
explicitly defined.
• If a single parameterized constructor is defined, it is necessary to explicitly
defined the default constructor. For the child class object to use it
EXAMPLE: ORDER OF CONSTRUCTOR CALL FOR
INHERITANCE
class Parent {
public: // main function
// base class constructor int main() {
Parent() {
cout << "Inside base class" << endl; // creating object of sub class
} Child obj;
}; Parent pobj;

// sub class return 0;


class Child : public Parent { }
public:
//sub class constructor
Child() { Output:
cout << "Inside sub class" << endl; Inside base class
} Inside sub class
}; Inside base class
NEED OF DEFAULT CONSTRUCTOR
class A{ class X: public A{
protected: public: int main() {
int a; int c; X x1(2,3,4);
public: X(int w, int e){ return 0;}
A(int a){ a=w;
cout<<"parameterized c=e;
constructor of Class A\n";}};
cout<<a<<endl<<c;}};

This code will through error, because child class object implicitly calls the parent class default
constructor. And in this case, class A have no default constructor.
CONSTRUCTOR CALL USING INITIALIZER
LIST
• To make the child class constructor to call the parent class’s parameterized constructor, a new
constructors needs to be defined in the child class which explicitly calls the parent class’s
parameterized constructor using initializer List
• Example:
X(int w, int e) : A(w){ Colon (:) followed by the Parent class
constructor call is the initializer list.
c=e;
cout<<“Param of child Class X is ”<<c; }
• This calls the constructor of parent Class (A) with argument w, before the body of the child
constructor executes
ORDER OF CONSTRUCTOR CALL FOR
MULTIPLE INHERITANCE
• For multiple inheritance order of constructor call is, the base class’s constructors are called in the
order of inheritance and then the derived class’s constructor.
class Parent1 { public:
public: Child() {
Parent1() cout << "Inside child class" << endl; } };
{
cout << "Inside first base class" << endl; }}; int main() {
Child obj1;
class Parent2 { return 0;
public: }
Parent2() {
cout << "Inside second base class" << endl; } }; Output:
Inside first base class
Inside second base class
Inside child class
class Child : public Parent1, public Parent2 {
DEFAULT ARGUMENTS
 Default argument is an argument to a function that a programmer is not required
to specify.
 C++ allow the programmer to specify default arguments that always have a

value, even if one is not specified when calling the function.

 For example, in the following function declaration: int MyFunc(int a, int b,

int c=12);
DEFAULT ARGUMENTS
◻The programmer may call this function in two ways:

• result =MyFunc(1, 2, 3);

• result =MyFunc(1, 2);

◻In the first case the value for the argument called c is specified as normal. In
the second one, the argument is omitted, and the default value of 12will be
used instead.

◻It is possible to define constructors with default arguments.


Some Important Points About
Constructors
◻Automatically called when an object is created.

◻We can define our own constructors

◻A constructor takesthe same name as the class name.


◻We can’t define a constructor in the private section.
Some Important Points About
Constructors
◻No return type is specified for a constructor.

◻Constructor mustbe defined in the public. The constructor must be a public


member.
◻Overloading of constructors is possible.

◻If an object is copied from another object then the copy constructor is called.
DESTRUCTORS
◻Destructors are special member functions.

◻Release dynamic allocated memory.

◻Destructors are automatically named.

◻Takes the same name of class name.

◻General Syntax of Destructors

~classname();
Some Important Points About
Destructors:
◻Take the same name as class name.

◻Defined in the public.

◻Destructors cannot be overloaded.

◻No return type is specified.


EXAMPLE
class creature{ }
private: };
int yearofBirth;
public:
creature(){
yearofBirth=1970; cout<<"constructure
called"<<endl;
}
~creature(){
cout<<"destructure called"<<endl;
EXAMPLE
int main()
{
cout<<"main start"<<endl;
{
creature obj;
}
cout<<"main end"<<endl;
return 0;
}
W H Y A R E DESTRUCTORS USEFUL?
• Useful for garbage collection

• Garbage-collected languages like JAVA do not have a destructor

• There is no guarantee of when an object will be destroyed


CONSTRUCTOR A N D DESTRUCTOR W H E N
MULTIPLE OBJECTS A R E CREATED
#include <iostream> main()
using namespace std; {
class Test { // Create multiple objects of the Test class
public: Test t, t1, t2, t3; return 0;
// User-Defined Constructor
Test() { }
cout << "\n Constructor executed"; }
// User-Defined Destructor
~Test() {
cout << "\n Destructor executed"; }
};
ORDER OF CONSTRUCTOR AND
DESTRUCTOR CALL

You might also like