Lecture 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Object Oriented Programming

(OOP)

Lecture 03

Engr. Dr. Ghulam Fareed Laghari

Department of Computer Science


Barani Institute of Management Sciences (BIMS)
1
Rawalpindi
2

CONTENT
Examples: Example 4
Examples: Example 4 Output
Examples: Example 4 Code Explanation
Examples: Example 5
Examples: Example 5 Output
Examples: Example 5 Code Explanation
Class Methods: Inside and Outside the Class
Class Methods: Outside the Class (Syntax)
Class Methods: Outside the Class (Example)
Class Methods: Outside the Class with Parameters
CONTENT
Constructors: Syntax
Constructors: Example
Constructors: Passing Parameters to Constructors
Constructors: Passing Parameters to Constructors (Example)
Constructors: Defining Outside the Class
Constructors: Defining Outside the Class (Example)
Constructors: How A Constructor Works (Example)

3
4

Examples: Example 4
 Example 4: Demonstrates the use of multiple classes and creating multiple objects from those classes.

#include <iostream> // Method to display car details


using namespace std; void displayCarInfo() {
cout << "Brand: " << brand << ", Model: " << model << ",
// Class Person Year: " << year << endl;
class Person { }
public: };
string name; int main() {
int age; // Creating objects of Person class
Person person1, person2;
// Method to display person details
void displayPersonInfo() { // Assigning values to person1
cout << "Name: " << name << ", Age: " << age << endl; person1.name = "Alice";
} person1.age = 28;
};
// Class Car // Assigning values to person2
class Car { person2.name = "Bob";
public: person2.age = 35;
string brand;
string model; // Creating objects of Car class
int year; Car car1, car2;
5

Examples: Example 4 Output


 Example 4: Demonstrates the use of multiple classes and creating multiple objects from those classes. [continued]

// Assigning values to car1 cout << "Car 1: ";


car1.brand = "Toyota"; car1.displayCarInfo(); // Output: Brand: Toyota,
car1.model = "Camry"; Model: Camry, Year: 2018
car1.year = 2018;
cout << "Car 2: ";
// Assigning values to car2 car2.displayCarInfo(); // Output: Brand: Honda,
car2.brand = "Honda"; Model: Civic, Year: 2020
car2.model = "Civic";
car2.year = 2020; return 0;
}
// Displaying person and car info
cout << "Person 1: "; OUTPUT
person1.displayPersonInfo(); // Output: Name: Alice, Age: 28 Person 1: Name: Alice, Age: 28
Person 2: Name: Bob, Age: 35
cout << "Person 2: ";
person2.displayPersonInfo(); // Output: Name: Bob, Age: 35 Car 1: Brand: Toyota, Model: Camry, Year: 2018
Car 2: Brand: Honda, Model: Civic, Year: 2020
6

Examples: Example 4 Code Explanation


 Example 4: Demonstrates the use of multiple classes and creating multiple objects from those classes.

 CODE EXPLANATION

1. Two Classes:

 Class Person: Has attributes name and age and a method displayPersonInfo() to display the details of a person.

 Class Car: Has attributes brand, model, and year and a method displayCarInfo() to display the details of a car.

2. Objects:

 We create two objects of the Person class: person1 and person2. Each has different values for name and age.

 We create two objects of the Car class: car1 and car2. Each has different values for brand, model, and year.

3. Method Calls:

 We use person1.displayPersonInfo() and person2.displayPersonInfo() to display the information of both Person objects.

 Similarly, car1.displayCarInfo() and car2.displayCarInfo() are used to display the information of both Car objects.
When we want to store numbers with 7
decimals, we can either use the float or
double.
However, doubles have twice the byte size
of floats. Also, doubles are more accurate
Examples: Example 5
when dealing with large decimal values.

 Example 5: A Bank Account class that implements a balance check mechanism, restricted withdrawal, and interest calculation.

#include <iostream> // Method to deposit money into the account


using namespace std; void deposit(double amount) {
if (amount > 0) {
// Class BankAccount balance += amount;
class BankAccount { cout << "Deposit successful. Current balance: $" <<
private: balance << endl;
string accountHolder; } else {
double balance; cout << "Invalid deposit amount." << endl;
double interestRate; // Interest rate in percentage }
}
public:
// Constructor to initialize the bank account with holder // Method to withdraw money from the account (with a
name, balance, and interest rate restriction on exceeding balance)
BankAccount(string name, double initialBalance, double void withdraw(double amount) {
rate) { if (amount > balance) {
accountHolder = name; cout << "Insufficient funds. Cannot withdraw $" <<
balance = initialBalance; amount << " from balance of $" << balance << endl;
interestRate = rate; }
}
8

Examples: Example 5
 Example 5: A Bank Account class that implements a balance check mechanism, restricted withdrawal, and… [continued]
else if (amount > 0) { int main() {

balance -= amount; // Creating a unique object with an initial balance and interest rate
cout << "Withdrawal successful. Current balance: $" << balance << BankAccount account1("John Doe", 500.0, 2.5); // 2.5% interest rate
endl;
} else { // Display account info
cout << "Invalid withdrawal amount." << endl; account1.displayAccountInfo(); // Output: Account Holder: John Doe,
} Balance: $500
}
// Method to apply annual interest // Try to withdraw more money than available (special case scenario)
void applyInterest() { account1.withdraw(600); // Output: Insufficient funds
double interest = (balance * interestRate) / 100;
balance += interest; // Deposit some money
cout << "Interest applied at " << interestRate << "%. Current balance: account1.deposit(200); // Output: Deposit successful. Current balance:
$" << balance << endl; $700
}
// Successful withdrawal
// Method to display account details account1.withdraw(300); // Output: Withdrawal successful. Current
void displayAccountInfo() { balance: $400
cout << "Account Holder: " << accountHolder << ", Balance: $" << // Apply interest
balance << endl; account1.applyInterest(); // Output: Interest applied at 2.5%. Current
} balance: $410
}; return 0;
}
9

Examples: Example 5 Output


 Example 5: A Bank Account class that implements a balance check mechanism, restricted withdrawal, and
interest calculation.

OUTPUT

Account Holder: John Doe, Balance: $500

Insufficient funds. Cannot withdraw $600 from balance of $500

Deposit successful. Current balance: $700


It shows how real-world
Withdrawal successful. Current balance: $400 scenarios can be modeled in
C++ using object-oriented
principles like data
Interest applied at 2.5%. Current balance: $410 encapsulation and method-
based logic enforcement.
10

Examples: Example 5 Code Explanation


 Example 5: A Bank Account class that implements a balance check mechanism, restricted withdrawal, and interest calculation.
 CODE EXPLANATION
1. INSUFFICIENT FUNDS SCENARIO: 4. WITHDRAWAL RESTRICTION:
 The method withdraw() checks if the requested amount exceeds  This class is designed to handle the special case where a
the current balance. If so, the withdrawal is denied, and an withdrawal is attempted for more money than is available in
appropriate message is displayed, ensuring that the account the account, ensuring that the withdrawal does not cause a
does not go into a negative balance. negative balance.
2. DEPOSIT AND WITHDRAWAL LOGIC: 5. INTEREST APPLICATION:
 The program ensures that only valid amounts (positive values)  The interest is applied using the applyInterest() method, which
can be deposited or withdrawn. Negative or zero values are adds a percentage of the balance as interest. This is a unique
considered invalid. aspect often not seen in simple examples.
3. INTEREST CALCULATION: 6. DATA ENCAPSULATION:
 The method applyInterest() calculates interest based on the  The attributes accountHolder, balance, and interestRate are
current balance and adds it to the account. The interest rate is encapsulated as private, ensuring they are only accessible
provided when the account is created and applied annually. through the class's public methods, which is good practice in
OOP.
11

Class Methods: Inside and Outside the Class


 Methods are functions associated with a class. Functions within a class can be defined in two ways:

 Inside the class definition.

 Outside the class definition.

 In the example below, a method named myMethod is defined within the class.

 NOTE: Methods are accessed in the same way as attributes—by creating an instance (object) of the class and utilizing the dot notation (.).

 EXAMPLE 1: INSIDE EXAMPLE

class MyClass { // The class int main() {


public: // Access specifier MyClass myObj; // Create an object of
void myMethod() { // Method/function MyClass
defined inside the class myObj.myMethod(); // Call the method
cout << "Hello World!"; return 0;
} }
};
12

Class Methods: Outside the Class (Syntax)


 To define a function outside the class, declare it within the class and then define it externally using the class name,
followed by the scope resolution operator ::, and the function name.

 SYNTAX: The syntax of defining a member function outside the class is as follows:
return_type class_name::function_name(parameters)
{ function body
}

COMPONENTS
 return_type: Indicates the type of value to be returned by the  function_name: The name of the member function to be
function. defined.
 class_name: Indicates the name of the class to which the  parameters: A list of parameters (if any) that the function
function belongs. accepts.
 ::: Scope resolution operator.  function body: The code that defines the function's behavior.
13

Class Methods: Outside the Class (Example)


 EXAMPLE 2: OUTSIDE EXAMPLE
class MyClass { // The class int main() {
public: // Access specifier MyClass myObj; // Create an object
void myMethod(); // Method/function of MyClass
declaration myObj.myMethod(); // Call the method
}; return 0;
}
// Method/function definition outside the
class
void MyClass::myMethod() {
cout << "Hello World!";
}
14

Class Methods: Outside the Class with Parameters


 EXAMPLE 3: OUTSIDE EXAMPLE: Adding PARAMETERS
#include <iostream> int main() {
using namespace std;
Car myObj; // Create an object of Car
class Car {
public: cout << myObj.speed(200); // Call the
int speed(int maxSpeed); method with an argument
};
return 0;
int Car::speed(int maxSpeed) { }
return maxSpeed;
}
15

Constructors: Syntax
 A constructor is a special member function that is automatically executed when an object of the class is created.

 It has no return type and shares the same name as the class, followed by parentheses ().

 A constructor functions like a normal function but cannot return any value. [i.e., programmer can't use a return statement to
return data from it.]

 It is typically used to initialize the class's data members. [i.e. Its purpose is to initialize the object, not to provide a result. It
implicitly (automatically) returns the created object itself when it completes, but programmer do not specify or control this return.]

 SYNTAX: The syntax for declaring a constructor is mentioned below:


constructor_name() {
constructor body
}

 NOTE: The constructor has the same name as the class, it is always public, and it does not have any return value.
16

Constructors: Example
Example 4:
#include <iostream> int main() {
using namespace std; MyClass myObj; // Create an object of
MyClass (this will call the constructor)
class MyClass { // The class return 0;
public: // Access specifier }
MyClass() { // Constructor
cout << "Hello World!";
}
};
17

Constructors: Passing Parameters to Constructors


Parameters are passed to a constructor in the same way as they are passed to regular functions.

The key difference is that parameters are passed to the constructor when the object is created.

Parameters are enclosed in parentheses, along with the object name, during the declaration.

SYNTAX: The syntax for passing parameters to constructor is mentioned below:

type object_name(parameters);
type: Represents the class name, indicating the type of object that will be instantiated.

object_name: Specifies the name of the object being created.

parameters: Lists the parameters that are provided to the constructor.


18

Constructors: Passing Parameters to Constructors (Example)


 Example 5:
class Car { // The class int main() {
public: // Access specifier // Create Car objects and call the constructor with different
string brand; // Attribute values
string model; // Attribute Car carObj1("BMW", "X5", 1999);
int year; // Attribute Car carObj2("Ford", "Mustang", 1969);
Car(string x, string y, int z) { // Constructor with parameters
brand = x; // Print values
model = y; cout << carObj1.brand << " " << carObj1.model << " " <<
year = z; carObj1.year << "\n";
} cout << carObj2.brand << " " << carObj2.model << " " <<
}; carObj2.year << "\n";
return 0;
}
19

Constructors: Defining Outside the Class


Constructors, similar to functions, can be defined outside the class.

Begin by declaring the constructor within the class.

Then, define the constructor outside the class using the following syntax:

Specify the class name.

Use the scope resolution operator ::.

Follow with the constructor name, which matches the class name.

SYNTAX:

class name::constructor name(parameter(s))


20

Constructors: Defining Outside the Class (Example)


Example 6:
class Car { // The class int main() {
public: // Access specifier // Create Car objects and call the constructor with different values
string brand; // Attribute Car carObj1("BMW", "X5", 1999);
string model; // Attribute Car carObj2("Ford", "Mustang", 1969);
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration // Print values
}; cout << carObj1.brand << " " << carObj1.model << " " <<
// Constructor definition outside the class carObj1.year << "\n";
Car::Car(string x, string y, int z) { cout << carObj2.brand << " " << carObj2.model << " " <<
brand = x; carObj2.year << "\n";
model = y; return 0;
year = z; }
}
21

Constructors: How A Constructor Works (Example)


 Example 7:
class Rectangle { int main() {
private:
int length; // Creating an object of Rectangle class
int width; Rectangle rect(10, 5); // Constructor is automatically

public: called here


// Constructor to initialize data members
Rectangle(int l, int w) {
length = l; // Calling a normal function to calculate area
width = w; cout << "Area: " << rect.calculateArea() << endl;
cout << "Constructor called. Length: " << length <<
", Width: " << width << endl;
} return 0;
// A normal function to calculate area OUTPUT
int calculateArea() { } Constructor called. Length: 10, Width: 5
return length * width; Area: 50
}
};
22

Constructors: How A Constructor Works (Example)


Example 7:
 CODE EXPLANATION:
 Constructor (Rectangle(int l, int w)):
 When the object rect is created with the arguments 10 and 5, the constructor is automatically called to
initialize the length and width data members of the object.
 It doesn't return any value. Its sole purpose is to initialize the object (in this case, to set the dimensions
of the rectangle).
 Normal Function (int calculateArea()):
 This is a regular function that returns the calculated area of the rectangle by multiplying length and
width.
 Unlike the constructor, this function explicitly returns an integer value (the area).
THANK YOU

ANY QUESTIONS?

23

You might also like