0% found this document useful (0 votes)
35 views34 pages

Encap-Constructors OOP

this contain informtion of encapsulation of oop

Uploaded by

Huriza Tahir
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)
35 views34 pages

Encap-Constructors OOP

this contain informtion of encapsulation of oop

Uploaded by

Huriza Tahir
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/ 34

Encapsulation

Content
Content
▪ Class and Object
▪ Encapsulation
▪ Data Hiding
▪ Access specifiers.
▪ Examples.
Class
“ A class in C++ is a user-defined type or data structure
declared with keyword class that has data and functions
as its members whose access is governed by the three
access specifiers private, protected or public.”
What is the
difference between
a class and an
object ?
Example
Example
Dog Class
Encapsulation
“ ? ”
Encapsulation
Cont..
Cont..
Cont..
“Encapsulation is an Object Oriented Programming
concept that binds together the data and functions that
manipulate the data, and that keeps both safe from outside
interference and misuse”
Advantages and Features of
encapsulation

▪ Encapsulation is used to reduce the complexity


and improve reusability.
▪ Encapsulation defines the interface clearly which
improves the readability and understandability.
▪ Encapsulation helps to hide important data and
ensures enhanced Security.
▪ The member variables and members are bundled
into a single unit as a class which makes the
maintenance easy.
▪ The encapsulated classes are straightforward and
are easy to manage and improves the future
development of the application.
Class Task
Design a C++ class, named RealEstateProperty, to represent
real estate properties while applying encapsulation principles
for controlled access to the property's price.
Define Data Members:

Choose an appropriate data member to represent the price, and specify why it's
declared as private.

Setter (setPrice):

Provide details on the setPrice function, including the validation it performs to


ensure the price remains within a reasonable range (e.g., 10,000 to 10,000,000).

Getter (getPrice):

Explain the role of the getPrice function in providing read-only access to the price.

Example Usage (in main):


Discuss the example usage in the main function, emphasizing how it showcases
the setter's functionality for both valid and invalid prices. Predict the expected
output messages.

Ensuring Encapsulation:
Elaborate on how the class design maintains encapsulation, preventing external
code from directly modifying the price through the private access modifier.
Write a C++ program that
creates a class called laptop. The
data members of the class are
brand (string), model
(string), serial (int), colour
(string), price (float),
processor speed (float), RAM
(int), screen that size(float).
Create member function will set
the individual values. Since the
RAM can be upgraded therefore
create a function that allows you
to upgrade the RAM only. In the
end, create a function that will
display all the data members.
What is a Constructor?
• A constructor is a member function with
the same name as the class.
• It is automatically called when an object of
the class is created.
• Constructors are used to initialize the
data members of the class and perform
any necessary setup operations.
• They ensure that objects are properly
initialized before they can be used.
Constructors can be overloaded to provide
different ways of initializing objects.
Example
Types of Constructors

1.Default Constructor
2.Parameterized Constructor
3.Copy Constructor
Default Constructor
• Takes no parameters.
• Purpose: Initializes object
attributes to default values.

Example:
Person() { name = "John"; age = 30; }
class Book {
Parameterized Constructor public:
Book(string title, string author, int pages) {
this->title = title;
A parameterized constructor takes one this->author = author;
or more parameters and initializes the this->pages = pages;
}
object's attributes based on those
parameters. void displayInfo() {
cout << "Title: " << title << ", Author: " << author <<
", Pages: " << pages << endl;
Book(string title, std::string author, int pages) }
{ /* Initialize attributes */ }
private:
string title;
string author;
int pages;
};
class Point {
public:
Copy Constructor Point(int x, int y) {
this->x = x;
• Creates a copy of an existing object. this->y = y;
}
• Used for creating deep copies.
Point(const Point& other) {
this->x = other.x;
Example: this->y = other.y;
}
Point(const Point& other) { /* Copy
void displayCoordinates() {
attributes */ } std::cout << "X: " << x << ", Y: " << y << std::endl;
}

private:
int x;
int y;
};
class Student {
public:
void displayInfo() {
// Default constructor
std::cout << "Roll Number: " << rollNumber << ",
Student() { Name: " << name << ", Age: " << age << std::endl;
rollNumber = 0; }
name = "Unknown";
age = 0; private:
int rollNumber;
} std::string name;
int age;
// Parameterized constructor };
Student(int roll, std::string n, int a) {
rollNumber = roll; int main() {
Student student1; // Calls the default constructor
name = n; student1.displayInfo();
age = a;
} Student student2(101, "Alice", 20); // Calls the
// Copy constructor parameterized constructor
student2.displayInfo();
Student(const Student& other) {
rollNumber = other.rollNumber; Student student3 = student2; // Calls the copy
name = other.name; constructor
age = other.age; student3.displayInfo();
}
return 0;
}
Class Task
Imagine you are tasked with creating a C++
program to represent books in BookWorld's
inventory. What attributes (data) would you
consider important to include in a Book class?
Provide at least three attributes and explain why
each is essential.

(b) How would you implement a default


constructor for the Book class? What values
would you assign to the attributes in the default
constructor, and why?

(c) To create a parameterized constructor for


the Book class that allows you to set the title,
author, price, genre, and special edition status
when creating a book object, what steps would
you take? Provide a code snippet to illustrate
this.
Constructor
•Overloading
Overloaded constructors essentially have the
same name (exact name of the class) and
different by number and type of arguments.
• A constructor is called depending upon the
number and type of arguments passed.
• While creating the object, arguments must
be passed to let compiler know, which
constructor needs to be called.
Destructors in C+ Syntax

+• A destructor is also a special member function like a ~ <class-name>() {


// some instructions
constructor. Destructor destroys the class objects
}
created by the constructor.
• Destructor has the same name as their class name
preceded by a tilde (~) symbol.
• It is not possible to define more than one destructor.
• The destructor is only one way to destroy the object
created by the constructor. Hence destructor can-not
be overloaded.
• Destructor neither requires any argument nor returns
any value.
• It is automatically called when an object goes out of
scope.
• Destructor release memory space occupied by the
objects created by the constructor.
• In destructor, objects are destroyed in the reverse of an
object creation.
Class Task
Write a C++ program that simulates a simple bank account system. The program should have the
following features:
Create a class named BankAccount with the following private member variables:
accountNumber (integer): to store the account number
balance (double): to store the account balance

Implement the following public member functions for the BankAccount class:

BankAccount(int accNumber, double initialBalance):Constructor to initialize the account number and


balance.
void deposit(double amount): Method to deposit money into the account.
void withdraw(double amount): Method to withdraw money from the account. Ensure that the
withdrawal amount does not exceed the current balance.
void display(): Method to display the account number and balance.
In the main function:

Create an object of the BankAccount class with an initial balance of $1000.


Deposit $500 into the account.
Withdraw $200 from the account.
Display the account details after each operation..
Conclusion
Constructors are a fundamental aspect of C++ programming.
They provide a way to initialize objects and ensure their
proper setup. By understanding constructors and their types,
you can build a strong foundation for your C++ programs.
Constructor initialization lists and constructor overloading
further enhance the flexibility and efficiency of your code.
Embrace constructors as powerful tools in your C++ journey.
Thanks!
Do you have any questions?
[email protected]

You might also like