0% found this document useful (0 votes)
3 views

(Ch7) Computer Programming

This document covers key concepts of Object-Oriented Programming in C++, including member and friend functions, inheritance types, function overloading, and exception handling. It provides definitions, examples, and syntax for each concept, emphasizing the importance of access specifiers, inline functions, template functions, and operator overloading. Additionally, it illustrates practical scenarios for single, multiple, and multilevel inheritance, along with exception handling techniques.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

(Ch7) Computer Programming

This document covers key concepts of Object-Oriented Programming in C++, including member and friend functions, inheritance types, function overloading, and exception handling. It provides definitions, examples, and syntax for each concept, emphasizing the importance of access specifiers, inline functions, template functions, and operator overloading. Additionally, it illustrates practical scenarios for single, multiple, and multilevel inheritance, along with exception handling techniques.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Unit VII: Object-Oriented Programming Concepts (8

hrs)
7.1 Inline function
7.2 Friend function
7.3 Function overloading
7.4 Inheritance and its types (single, multiple and
multi level)
7.5 Function overriding
7.6 Template function
7.7 Exception handling
Member and Friend Functions in C++

1. Member Functions
-​ Definition:
-​ A member function is a function defined inside a class that
operates on the data members of the class.
-​ It has access to all the attributes (data members) and
methods of the class.

Access Specifiers for Member Functions


1.​Public:

-​ Member functions declared under the public access


specifier can be accessed from anywhere in the program
using an object of the class.
-​ Used for methods that need to interact with users or
external code.
-​ Example:
class MyClass {
public:
void display() {
cout << "Public member function!" << endl;
}
};
int main() {
MyClass obj;
obj.display(); // Accessible
return 0;
}
2.​Private:

-​ Member functions declared under the private access


specifier can only be accessed within the class itself.
-​ They are usually helper functions or internal utility
functions.
-​ Example:
class MyClass {
private:
void secretFunction() {
cout << "Private member function!" << endl;
}
public:
void accessSecret() {
secretFunction(); // Called within the class
}
};
int main() {
MyClass obj;
obj.accessSecret(); // Indirectly calls the private function
return 0;
}
3.​Protected:

-​ Member functions declared under the protected access


specifier can be accessed within the class itself and its
derived classes (via inheritance).
-​ Example:
class Base {
protected:
void protectedFunction() {
cout << "Protected member function!" << endl;
}
};
class Derived : public Base {
public:
void accessProtected() {
protectedFunction(); // Accessible within derived class
}
};
int main() {
Derived obj;
obj.accessProtected();
return 0;
}

2. Friend Functions
-​ Definition:
-​ A friend function is a non-member function that has access
to the private and protected members of a class.
-​ Declared using the friend keyword inside the class.
-​ Used when a function needs to operate on
private/protected data but is not logically a part of the class.

Access Specifiers for Friend Functions


-​ A friend function is not restricted by the access specifiers (public,
private, protected) of the class.
-​ Even if private or protected members of a class are involved, a
friend function can directly access them.
Example:
#include<iostream>
using namespace std;
class MyClass {
private:
int privateData;
public:
MyClass(int val) {
​ privateData = val;
}

// Friend function declaration


friend void displayPrivate(const MyClass &obj);
};
void displayPrivate(const MyClass &obj) {
cout << "Private Data: " << obj.privateData << endl; // Access
private data
}
int main() {
MyClass obj(42);
displayPrivate(obj); // Calls the friend function
return 0;
}
Output:
Private Data: 42
Key Differences Between Member and Friend Functions
Aspect Member Function Friend Function

Access Specifiers Restricted by access Can access private


specifiers and protected
members regardless
of access specifiers

Belongs to Class Yes No

Called By Called using an Called like a normal


object of the class function

Usage Operates as part of Operates outside the


the class class
Types of Inheritance:

Single Inheritance Scenario: Bank Account System


Let's create a simple banking system using single inheritance, where:
-​ The BankAccount class (Base Class) manages general account details.
-​ The SavingsAccount class (Derived Class) extends BankAccount and adds
interest calculation.

Class Design

Base Class: BankAccount


-​ Attributes:
-​ accountNumber (string) – Stores the account number.
-​ holderName (string) – Stores the account holder’s name.
-​ balance (double) – Stores the account balance.

-​ Functions:
-​ deposit(double amount): Adds money to the account.
-​ withdraw(double amount): Deducts money if sufficient
balance is available.
-​ display() – Displays account details.

Derived Class: SavingsAccount (Inherits BankAccount)


-​ Additional Attribute:
-​ interestRate (double) – Stores interest rate (default 5%).

-​ Additional Functions:
-​ calculateInterest() – Computes and adds interest to
balance.
-​ display() – Displays account details including interest rate.
Multiple Inheritance Scenario: Employee Payroll System

Let's design a realistic and easy-to-implement scenario using


multiple inheritance.

Problem Statement:

We need to create a payroll system where:

●​ The Person class stores general information like name and age.
●​ The Job class stores job-related details like designation and salary.
●​ The Employee class inherits from both Person and Job to create a complete
employee record.

1️⃣ Base Class: Person

●​ Attributes:​
name (string) – Stores the employee’s name.​
age (int) – Stores the employee’s age.
●​ Functions:​
displayPerson() – Displays personal details.

2️⃣ Base Class: Job

●​ Attributes:​
designation (string) – Stores job title.​
salary (double) – Stores salary.
●​ Functions:​
displayJob() – Displays job details.

3️⃣ Derived Class: Employee (Inheriting from Person and Job)

●​ Additional Functions:​
displayEmployee() – Displays both personal and job details.
Multilevel Inheritance Scenario: Vehicle Hierarchy System

Problem Statement:
We need to design a vehicle classification system using multilevel inheritance, where:

●​ Vehicle (Base Class) stores general vehicle attributes.


●​ Car (Intermediate Derived Class) extends Vehicle with car-specific details.
●​ ElectricCar (Final Derived Class) extends Car to include electric vehicle properties.

1️⃣ Base Class: Vehicle


●​ Attributes:
○​ brand (string) – Stores the vehicle brand.
○​ model (string) – Stores the vehicle model.
○​ year (int) – Stores the manufacturing year.
●​ Functions:
○​ displayVehicle() – Displays basic vehicle details.

2️⃣ Intermediate Derived Class: Car (Inherits from Vehicle)


●​ Additional Attributes:
○​ seatingCapacity (int) – Stores number of seats.
○​ fuelType (string) – Stores fuel type (Petrol/Diesel/Electric).
●​ Additional Functions:
○​ displayCar() – Displays car details.

3️⃣ Final Derived Class: ElectricCar (Inherits from Car)


●​ Additional Attributes:
○​ batteryCapacity (double) – Stores battery capacity in kWh.
○​ rangePerCharge (int) – Stores range in km per full charge.
●​ Additional Functions:
○​ displayElectricCar() – Displays electric car details.
Inline Functions
●​ Definition: Inline functions are a request to the compiler to
replace the function call with the actual code of the function,
reducing function call overhead.

●​ Syntax:

inline returnType functionName(parameters) {


// Function body
}

●​ Key Points:
○​ Performance:
■​ Eliminates the overhead of a function call.
■​ Suitable for small, frequently called functions.
○​ Compiler Decision:
■​ The inline keyword is a request, not a command; the
compiler may ignore it.
○​ Use Cases:
■​ For small, performance-critical functions.
■​ Example: Getter functions in classes.
○​ Drawbacks:
■​ Code bloat if overused (increases binary size).
■​ Not suitable for large functions.
○​ Example:
inline int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3); // No function call overhead
}
Template Functions

Definition:
Template functions allow the creation of functions that can operate on
different data types without rewriting the function for each type. The
compiler generates a specific version of the function based on the
type used during the function call.

Detailed Syntax:
template <typename T>
returnType functionName(T parameter) {
// Function body
}
-​ template: Declares that the function uses a template.
-​ <typename T>: Defines a type parameter T (can also use class T
instead of typename T).

Key Features:

1. Generic Programming
-​ Enables code reuse for different data types.
-​ Reduces redundancy and makes code more maintainable.

2. Type Inference
-​ The compiler automatically determines the type of the arguments
when the function is called.

3. Multiple Template Parameters


-​ You can define a function with multiple template parameters.
-​ Syntax:
template <typename T1, typename T2>
returnType functionName(T1 param1, T2 param2) {
// Function body
}

Examples:

Basic Template Function


template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << getMax(10, 20) << endl; // Works for int
cout << getMax(5.5, 3.3) << endl; // Works for double
return 0;
}

Template with Multiple Parameters


template <typename T1, typename T2>
void printPair(T1 a, T2 b) {
cout << "First: " << a << ", Second: " << b << endl;
}
int main() {
printPair(10, 20.5); // First: 10, Second: 20.5
printPair("Hello", 100); // First: Hello, Second: 100
return 0;
}

Using Default Template Arguments


-​ You can provide a default type for the template parameter.

template <typename T = int>


T add(T a, T b) {
return a + b;
}
int main() {
cout << add(5, 10) << endl; // Uses default type (int)
cout << add<double>(5.5, 3.3) << endl; // Explicitly specifies double
return 0;
}

Template Specialization
-​ Used to define a specific implementation of a template for a
particular data type.
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
// Specialization for const char*
template <>
const char* getMax<const char*>(const char* a, const char* b) {
return (strcmp(a, b) > 0) ? a : b;
}
int main() {
cout << getMax(10, 20) << endl; // Uses generic template
cout << getMax("Apple", "Banana") << endl; // Uses specialized
template
return 0;
}
Exception Handling in C++
Exception handling is a mechanism in C++ to handle runtime errors
gracefully, preventing crashes and ensuring the program continues to
execute.

Key Components:
1.​try block:
-​ Code that might throw an exception is enclosed in a try
block.
-​ Syntax:
try {
// Code that may throw an exception
}

2.​catch block:
-​ Handles the exception thrown in the try block.
-​ Syntax:
catch (exceptionType identifier) {
// Code to handle the exception
}
3.​throw statement:
-​ Used to explicitly throw an exception.
-​ Syntax:
throw exceptionValue;

Example:
#include <iostream>
using namespace std;
int divide(int a, int b) {
if (b == 0) {
throw "Division by zero!"; // Throwing an exception
}
return a / b;

}
int main() {
try {
cout << divide(10, 2) << endl; // Normal case
cout << divide(10, 0) << endl; // Exception case
} catch (const char* e) {
cout << "Error: " << e << endl; // Handling the exception
}
return 0;
}

Key Features:
1.​Multiple catch blocks:
-​ Handle different types of exceptions separately.
try {
// Code
} catch (int e) {
cout << "Integer exception: " << e << endl;
} catch (double e) {
cout << "Double exception: " << e << endl;
}

2.​Generic Catch (...):


-​ Catches all exceptions not explicitly handled.
catch (...) {
cout << "Unknown exception occurred!" << endl;
}
3.​Standard Exceptions (std::exception):
-​ C++ provides a hierarchy of exceptions in <exception>
header.
-​ Example:
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
try {
throw runtime_error("Runtime error occurred!");
} catch (const exception& e) {
cout << "Exception: " << e.what() << endl;
}
return 0;
}
4.​Custom Exceptions:
-​ Create your own exception class.
class MyException : public exception {
public:
const char* what() const noexcept override {
return "Custom exception occurred!";
}
};
int main() {
try {
throw MyException();
} catch (const MyException& e) {
cout << e.what() << endl;
}
return 0;
}
Function Overloading

Definition:
Function overloading allows defining multiple functions with the same
name but different parameter lists. The compiler determines which
function to invoke based on the arguments passed.

Key Points:
-​ Functions must differ in the number or types of parameters.
-​ Return type alone cannot distinguish overloaded functions.

Syntax:
void print(int x) {
cout << "Integer: " << x << endl;
}
void print(double y) {
cout << "Double: " << y << endl;
}
void print(string z) {
cout << "String: " << z << endl;
}
int main() {
print(5); // Calls print(int)
print(3.14); // Calls print(double)
print("Hello"); // Calls print(string)
return 0;
}

Advantages:
-​ Improves code readability.
-​ Reduces the need for function naming complexity.
Operator Overloading

Definition:
Operator overloading allows redefining the behavior of operators (e.g.,
+, -, *) for user-defined types (classes).

Key Points:
-​ Overloaded operators must be defined as class member
functions or friend functions.
-​ Some operators (e.g., ::, sizeof, .) cannot be overloaded.

Syntax:
class Complex {
double real, imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
// Overloading the + operator
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(1.2, 2.3), c2(3.4, 4.5);
Complex c3 = c1 + c2; // Calls operator+()
c3.display(); // Output: 4.6 + 6.8i
return 0;
}

Overloadable Operators:
+, -, *, /, %, =, ==, !=, >, <, [], (), ++, --, etc.
Function Overriding

Definition:
Function overriding allows redefining a base class function in a
derived class to provide a specific implementation.

Key Points:
-​ The base class function must be marked as virtual to allow
overriding.
-​ The function signature (name, parameters, and return type) in
the derived class must exactly match the base class function.

Syntax:
class Base {
public:
virtual void show() {
cout << "Base class function" << endl;
}
};
class Derived : public Base {
public:
void show() override { // Overrides Base::show()
cout << "Derived class function" << endl;
}
};
int main() {
Base* obj = new Derived();
obj->show(); // Calls Derived::show()
delete obj;
return 0;
}
Key Features:
-​ Enables runtime polymorphism.
-​ The override keyword ensures the function in the derived class
overrides the base class function.

Operator Overriding
-​ Technically, operator overriding doesn’t exist in C++
terminology, but operators can be redefined in derived classes
when inherited from a base class. This typically involves
overriding a base class function used to implement the operator.

Example:
class Base {
public:
virtual int operator()(int x) { // Callable object (functor)
return x * x;
}
};
class Derived : public Base {
public:
int operator()(int x) override { // Overrides operator()
return x + x;
}
};
int main() {
Base* obj = new Derived();
cout << (*obj)(5) << endl; // Calls Derived::operator()
delete obj;
return 0;
}
Comparison Between Overloading and Overriding
Aspect Function/Operator Function/Operator
Overloading Overriding

Definition Same function/operator Redefining a base class


name but different function in the derived
parameter list. class.

Polymorphism Achieves compile-time Achieves runtime


polymorphism. polymorphism.

Relationship Functions exist in the Functions exist in a


same scope. base-derived
relationship.

Return Type Return type can differ Must match the base
(with explicit casting). class function.

Keyword No specific keyword Requires virtual in the


required. base class and override
in the derived class.

You might also like