(Ch7) Computer Programming
(Ch7) Computer Programming
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.
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.
Class Design
- Functions:
- deposit(double amount): Adds money to the account.
- withdraw(double amount): Deducts money if sufficient
balance is available.
- display() – Displays account details.
- Additional Functions:
- calculateInterest() – Computes and adds interest to
balance.
- display() – Displays account details including interest rate.
Multiple Inheritance Scenario: Employee Payroll System
Problem Statement:
● 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.
● Attributes:
name (string) – Stores the employee’s name.
age (int) – Stores the employee’s age.
● Functions:
displayPerson() – Displays personal details.
● Attributes:
designation (string) – Stores job title.
salary (double) – Stores salary.
● Functions:
displayJob() – Displays job details.
● 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:
● Syntax:
● 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.
Examples:
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;
}
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
Return Type Return type can differ Must match the base
(with explicit casting). class function.