0% found this document useful (0 votes)
4 views14 pages

Constructors and encapsulation

Uploaded by

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

Constructors and encapsulation

Uploaded by

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

What is a Constructor?

A constructor is a special function that is automatically called when an object of


a class is created. It helps initialize the object with default or specified values,
setting up the starting state of the object.

Key Points:

● The constructor has the same name as the class.


● It has no return type, not even void.
● It is called automatically when an object is created.

Real-Life Example of a Constructor

Think about setting up a new smartphone:

1. When you first turn on the phone (creating an object), it goes through
some initial setups—choosing language, connecting to Wi-Fi, etc.
2. This setup is similar to a constructor. It gets the phone ready to use as
soon as you turn it on.

Code Example: Constructor in C++

Here’s a simple example of a constructor in a Student class:

#include <iostream>
using namespace std;

class Student {
private:
string name;
int age;

public:
// Constructor to initialize name and age
Student(string studentName, int studentAge) {
name = studentName;
age = studentAge;
cout << "Constructor called: " << name << " is
created." << endl;
}

// Function to display student information


void displayInfo() {
cout << "Name: " << name << ", Age: " << age <<
endl;
}
};

int main() {
// Creating a Student object with name and age
Student student1("Alice", 16);
student1.displayInfo();

Student student2("Bob", 17);


student2.displayInfo();

return 0;
}

In this example:

1. When we create Student student1("Alice", 16);, the


constructor initializes name with "Alice" and age with 16.
2. The constructor is called automatically whenever we create a new
Student object.

What is a Destructor?
A destructor is a special function that is automatically called when an
object goes out of scope or is deleted. It helps clean up resources, like
freeing memory if necessary.

Key Points:

● The destructor has the same name as the class but starts with a
tilde (~), like ~Student().
● It has no return type and takes no parameters.
● It is called automatically when an object is destroyed (e.g., when it
goes out of scope or the program ends).
Real-Life Example of a Destructor

Imagine you’re done using a smartphone app. You:

1. Close the app, which saves data, releases memory, and stops using
resources.
2. Similarly, a destructor ensures an object’s resources are released
when it’s no longer needed.
Code Example: Destructor in C++

Let’s add a destructor to our Student class:

#include <iostream>
using namespace std;

class Student {
private:
string name;
int age;

public:
// Constructor
Student(string studentName, int studentAge) {
name = studentName;
age = studentAge;
cout << "Constructor called: " << name << " is
created." << endl;
}

// Destructor
~Student() {
cout << "Destructor called: " << name << " is
destroyed." << endl;
}

// Function to display student information


void displayInfo() {
cout << "Name: " << name << ", Age: " << age <<
endl;
}
};

int main() {
Student student1("Alice", 16);
student1.displayInfo();

Student student2("Bob", 17);


student2.displayInfo();

// Destructor is automatically called for student1 and


student2 when main ends
return 0;
}

In this example:
1. The constructor initializes each Student with name and age values
when an object is created.
2. The destructor is called automatically when the program ends (or
when objects go out of scope).
○ ~Student() prints a message, so we know when an object is
destroyed.

CONSTRUCTORS VS DECONSTRUCTORS

S.
Constructor Destructor
No.

Constructor helps to initialize Whereas destructor is used


1.
the object of a class. to destroy the instances.

It is declared as className( Whereas it is declared as ~


2. arguments if any ){Constructor’s className( no arguments
Body }. ){ }.
Constructor can either accept While it can’t have any
3.
arguments or not. arguments.

A constructor is called when an It is called while object of


4. instance or object of a class is the class is freed or
created. deleted.

Constructor is used to allocate While it is used to


5. the memory to an instance or deallocate the memory of
object. an object of a class.

While it can’t be
6. Constructor can be overloaded.
overloaded.

Here, its name is also same


The constructor’s name is same
7. as the class name preceded
as the class name.
by the tiled (~) operator.
In a class, there can be multiple While in a class, there is
8.
constructors. always a single destructor.

There is a concept of copy


constructor which is used to While here, there is no copy
9.
initialize an object from another destructor concept.
object.

They are often called in


They are often called in
10. reverse order of
successive order.
constructor.

FFD
#include <iostream>
using namespace std;

class Z
{
public:
// constructor
Z()
{
cout<<"Constructor called"<<endl;
}

// destructor
~Z()
{
cout<<"Destructor called"<<endl;
}
};

int main()
{
Z z1; // Constructor Called
int a = 1;
if(a==1)
{
Z z2; // Constructor Called
} // Destructor Called for z2
} // Destructor called for z1

Output:

Constructor called
Constructor called
Destructor called
Destructor called
ENCAPSULATION

What is Encapsulation?

Encapsulation is like putting everything that belongs together in a


secure box. In programming, we put data (variables) and methods
(functions) together in a single unit called a class. This “box” helps
protect data so it’s not accessed or modified directly. Instead, you
have a controlled way to access and modify it.

Real-Life Example: Encapsulation in a Bank Account

Imagine a bank account. You can:

● Deposit money.
● Withdraw money.
● Check your balance.

But you don’t have direct access to the bank's computer system to
change your balance, as that would be unsafe. Instead:

1. You use an ATM or bank app (methods) to access and update


your balance.
2. You don’t see how the bank internally manages your balance
(data is hidden).

This is encapsulation: the data (balance) is kept safe within a class,


and you can only interact with it through specific methods (deposit,
withdraw).

Code Example: Encapsulation with Bank Account Class

In C++, let’s create a simple BankAccount class to show


encapsulation. Here, the balance is private, so we can't directly
access or change it. Instead, we’ll use public methods to deposit or
withdraw money.

#include <iostream>
using namespace std;

class BankAccount {
private:
double balance; // Private: can only be accessed
within this class

public:
// Constructor to initialize balance
BankAccount(double initialBalance) {
balance = initialBalance;
}

// Public method to get the balance (getter)


double getBalance() {
return balance;
}

// Public method to deposit money


void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited $" << amount << endl;
}
}

// Public method to withdraw money


void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
cout << "Withdrew $" << amount << endl;
} else {
cout << "Insufficient balance" << endl;
}
}
};

In this example:

1. balance is private, so we can't change it directly from outside


the BankAccount class.
2. We use a public getter (getBalance()) to read the balance.
3. We use public methods (deposit and withdraw) to modify
the balance.

Private, Protected, and Public Access Specifiers

● Private: Only the class itself can access private members (like
balance in this example).
● Public: Anyone can access public members, such as
getBalance, deposit, and withdraw.
● Protected: Similar to private, but classes derived from this class
can access protected members.

Getters and Setters Explained


Getters and setters help you control how data is accessed or
modified:

● Getter: Retrieves (reads) a private variable.


● Setter: Updates (writes) to a private variable.
Example of Getters and Setters in Code

Let's add a setBalance function to illustrate a setter. Usually, we want


to control balance so it doesn’t go negative, so let’s limit setting
balance to positive values.

#include <iostream>
using namespace std;

class BankAccount {
private:
double balance;

public:
// Constructor to initialize balance
BankAccount(double initialBalance) {
balance = (initialBalance > 0) ? initialBalance
: 0;
}

// Getter for balance


double getBalance() {
return balance;
}

// Setter for balance (only allows positive values)


void setBalance(double newBalance) {
if (newBalance >= 0) {
balance = newBalance;
} else {
cout << "Balance cannot be negative" <<
endl;
}
}
};

int main() {
BankAccount myAccount(100); // Create an account
with $100

// Using getter to see balance


cout << "Initial Balance: $" <<
myAccount.getBalance() << endl;

// Using setter to change balance


myAccount.setBalance(150);
cout << "New Balance: $" << myAccount.getBalance()
<< endl;

// Trying to set a negative balance


myAccount.setBalance(-50); // This will print an
error message
return 0;
}

Explanation of Code
1. Private Variable: balance is private, meaning it’s hidden from
outside the class.
2. Getter: getBalance() allows us to read the balance without
modifying it.
3. Setter: setBalance(double newBalance) allows us to
change the balance but only if the new balance is positive. This
keeps our data safe and valid.

Summary

● Encapsulation is like using an ATM for accessing your bank


account. You can’t see or touch the actual bank's database; you
use certain methods.
● Private members are hidden and only accessible within the
class.
● Getters and setters help us control access to data, keeping it
safe and valid.

More About Encapsulation in c++

You might also like