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

Object Orianted Programming-201-1

The document covers key concepts in Software Engineering and Object-Oriented Programming (OOP) with a focus on polymorphism in C++, file handling, exception handling, and data structures. It explains compile-time and runtime polymorphism, file operations using the fstream library, and the importance of exception handling for robust programming. Additionally, it highlights common data structures in C++ and their significance in efficient data management.

Uploaded by

haederredha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Object Orianted Programming-201-1

The document covers key concepts in Software Engineering and Object-Oriented Programming (OOP) with a focus on polymorphism in C++, file handling, exception handling, and data structures. It explains compile-time and runtime polymorphism, file operations using the fstream library, and the importance of exception handling for robust programming. Additionally, it highlights common data structures in C++ and their significance in efficient data management.

Uploaded by

haederredha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Software Engineering/OOP

Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

1. Polymorphism in C++
Polymorphism, a cornerstone of Object-Oriented Programming (OOP), is a
powerful concept that allows objects of different classes to be treated as
objects of a common type. It's like having a single interface that can
interact with diverse entities, making your code more flexible, reusable,
and maintainable. Polymorphism, derived from Greek words meaning
"many forms," refers to the ability of an object to take on multiple forms.
In simpler terms, it means that the same entity can exhibit different
behaviors in different contexts. There is two types of Polymorphism which
are:

1. Compile-Time Polymorphism (Static Polymorphism):


o Achieved through function overloading and operator overloading.
o The compiler determines which function to call at compile time
based on the number and types of arguments.

2. Runtime Polymorphism (Dynamic Polymorphism):


o Achieved through function overriding and virtual functions.
o The decision on which function to call is made at runtime based on
the actual object type.

1.1 Function Overloading


Function overloading allows you to define multiple functions with the
same name but different parameters. 1
The compiler selects the
appropriate function based on the arguments passed during the call.

int add(int a, int b) {


return a + b;
}

double add(double a, double b) {


return a + b; }

Key Points of Overloading:

1
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

 Same Scope: All overloaded functions must be in the same scope.

2
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

 Compile-time Polymorphism: The function to be called is


determined at compile time based on the function signature.

#include <iostream>
using namespace std;

void display(int i) {
cout << "Integer: " << i << endl;
}

void display(double f) {
cout << "Double: " << f << endl;
}

void display(string s) {
cout << "String: " << s << endl;
}

int main() {
display(5);
display(3.14);
display("Hello");
return 0;
}

1.2 Operator Overloading


Operator overloading allows you to redefine the behavior of operators (like +,
-, *, /, etc.) for user-defined data types (classes).

class Complex {
public:
Complex operator+(const Complex& other) const {
// ...
}
};

1.3 Function Overriding


Function overriding occurs when a derived class provides a specific
implementation for a function that is already defined in its base class.
In another words, Function

3
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

overriding occurs when a derived class has a definition for one of the
member functions of the base class. That base function is overridden in
the derived class.

class Animal {
public:
virtual void makeSound() {
cout << "Generic animal sound" << endl;
}
};

class Dog : public Animal {


public:
void makeSound() override {
cout << "Woof!" << endl;
}
};

Key Points of Function Overriding:

 Inheritance: Overriding functions must be in different classes that


have an inheritance relationship.
 Run-time Polymorphism: The function to be called is determined at
runtime based on the object type.
 Virtual Function: The base class function must be declared with
the virtual
keyword.

#include <iostream>
using namespace std;

class Base {
public:
virtual void show() {
cout << "Base class" << endl;
}};
class Derived : public Base {
public:
void show() override {
cout << "Derived class" << endl;
}};
int main() {
4
Base* b;
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

Derived d;
b = &d;
b->show();
return 0;}

1.4 Virtual Functions and Abstract Classes


 Virtual Functions: A virtual function in the base class indicates that
its implementation can be overridden in derived classes.
 Abstract Classes: A class containing at least one pure virtual function
(a virtual function with no implementation, declared using = 0) is
called an abstract class.

1.5 Benefits of Polymorphism


 Code Reusability: Reduces code duplication and improves
maintainability.
 Flexibility: Allows for more flexible and adaptable code.
 Extensibility: Makes it easier to add new classes and functionalities
without modifying existing code.
 Improved Design: Encourages better object-oriented design
principles.

2. Files in C++
File handling in C++ is a crucial aspect that allows programs to read from
and write to files. Imagine a program that calculates something, but when
you close it, all the data is lost. Files provide a way to store information
permanently, so your programs can read, write, and manipulate data
across multiple runs. Think of saving a game, storing user settings, or
processing large datasets – all rely on file handling. This enables data
persistence, making it possible to store information even after the
program has ended. C++ provides a comprehensive set of classes for file
operations as part of its Standard Library. The fstream library provides
tools for working with files, including reading, writing, and appending
data.

2.1 Types of Files:


C++ primarily deals with two types of files:
 Text Files: These store data as plain text, readable by any text
editor. Each character is represented by its ASCII value. Good for
configuration files, logs, and simple data storage.
 Binary Files: These store data in a binary format, which is more
efficient for storing complex data structures like objects or images.
Not directly human- readable.

2.2 Working with Files in C++:

5
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali
We use the fstream library, which provides classes for file input and
output. Here are the key classes:

 ofstream: For output (writing) to files.

6
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

 ifstream: For input (reading) from files.


 fstream: For both input and output operations.

2.3 Opening a File:


Before you can work with a file, you need to open it. To create an object of
one of the above classes and use the open() method. Here's how:

#include <iostream>
#include <fstream>

int main() {
std::ofstream myFile("my_data.txt"); // Opens "my_data.txt" for writing

if (myFile.is_open()) {
// File opened successfully
myFile << "Hello, File!" << std::endl; // Writing to the file
myFile.close(); // Closing the file is crucial!
} else {
std::cerr << "Unable to open file" << std::endl;
return 1; // Indicate an error
}

return 0;
}

2.4 File Modes:


When opening a file, you can specify a mode to control how it's accessed:
 ios::app (Append): Adds new data to the end of the file.
 ios::ate (At End): Sets the initial position to the end of the file.
 ios::in (Input): Opens the file for reading (default for ifstream).
 ios::out (Output): Opens the file for writing (default for ofstream).
Caution: This mode will overwrite the file's contents if it exists.
 ios::trunc (Truncate): Deletes the file's contents if it exists.
 ios::binary (Binary): Opens the file in binary mode.

You can combine modes using the bitwise OR operator (|):


std::ofstream myFile("my_data.txt", std::ios::app |
std::ios::binary);
// Append in binary mode

2.5 Reading from a File:


To read from a file, you can use the >> operator or the getline() function.

#include <iostream>
#include <fstream>
#include <string>

int main() {

7
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

std::ifstream

myFile("my_data.txt"); if

(myFile.is_open()) {

std::string line;

while (std::getline(myFile, line)) { // Read line by

line std::cout << line << std::endl;

// Here is how to use >> for reading

from file int number;


std::string word;

// Reading integers and strings from the file using the >>

operator while (myFile >> number >> word) {


std::cout << "Number: " << number << ", Word: " <<
word << std::endl;

myFile.close();

} else {

// ... error handling ...

return 0;
2.6 Writing to a File:
You can use the << operator to write various data types:

#include <iostream>
#include <fstream>

int main() {
std::ofstream outfile("example.txt");

if (outfile.is_open()) {
outfile << "This is a line." <<
std::endl; outfile << "This is another
line." << std::endl;

8
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

outfile.close();
} else {
std::cout << "Unable to open file." << std::endl;
}
return 0;
}

2.7 Error Handling:


Always check if a file opened successfully using is_open(). This prevents
your program from crashing if the file doesn't exist or there's a permission
issue. Use std::cerr for error messages. std::cerr is a standard error stream in
C++ used to output error messages. Unlike std::cout, std::cerr is unbuffered, meaning
that the output appears immediately. This makes it particularly useful for printing error
messages, as they are displayed as soon as they occur.

#include <iostream>
#include <fstream>
#include <string>

int main() {

std::ifstream

infile("example.txt"); if (!

infile) {

std::cerr << "Error: Could not open the file." <<

std::endl; return 1; // Exit the program with an

error code

} else {

std::string line;

while (getline(infile, line))

{ std::cout << line <<

std::endl;

infile.close();

9
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

2.8 Closing Files:


It's essential to close files using close() when you're finished with them.
This flushes any remaining data in the buffer to the file and releases the
file handle.

Key Takeaways:
 Include <fstream> for file operations.
 Use ofstream, ifstream, or fstream objects.
 Open files with appropriate modes.
 Always check for errors when opening files.
 Close files when finished.
 Use getline() for reading text files line by line.
 Use read() and write() for binary files.

3. Exception Handling in C++


Handling of exception enables programmer to write more robust and
efficient programs. Exception handling in C++ provides a way to react to
exceptional circumstances when runtime errors occur in programs by
transferring control to special functions called handlers. These functions
let the program not stopping and keep working to the next line. Runtime
errors like Division by Zero, Null Pointer Dereference, or Array Index Out
of Bounds. There are three reserved words for functions that make the
exception handling works, which are:

 try: Block of code to be tested for errors.


 catch: Block of code to handle the error.
 throw: Used to throw an exception.

Here is an example for simple exception handling:

#include <iostream>

int main()
{ try {
// Code that may throw an exception
throw 20;
} catch (int e) {
// Code to handle the exception
std::cerr << "An exception occurred. Exception Nr. " << e << std::endl;
}
return 0;
}

Throwing an Exception: Use the throw keyword to signal an error or an


unusual condition.
Catching an Exception: Use a catch block to handle the exception.
Try Block: Enclose the code that may throw an exception within a try block.

10
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

3.1 Types of Exceptions


Standard Exceptions: C++ provides a set of standard exceptions defined in the <stdexcept>
header.

#include <stdexcept>

throw std::runtime_error("Runtime error occurred");

Custom Exceptions: You can define your own exceptions by inheriting from the std::exception
class.
#include <iostream>
#include <exception>

class MyException : public std::exception {


public:
const char* what() const noexcept override
{ return "My custom exception";
}
};
int main()
{ try {
throw MyException();
} catch (const MyException& e)
{ std::cerr << e.what() << std::endl;
}
return 0;
}

Here is a practical example that demonstrates exception handling for


division by zero:
#include <iostream>
#include <stdexcept>

double divide(double numerator, double denominator)


{ if (denominator == 0) {
throw std::invalid_argument("Division by zero");
}
return numerator / denominator;
}
int main()
{ try {
std::cout << divide(10, 2) << std::endl; // 5
std::cout << divide(10, 0) << std::endl; // Exception
} catch (const std::invalid_argument& e)
{ std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}

11
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

Detailed Breakdown

1. try Block:
o Code that might throw an exception is enclosed within the try
block.
o If an exception is thrown, the program immediately jumps to
the corresponding catch block, skipping the remaining code in
the try block.
2. throw Statement:

 In the divide function, if the denominator is zero, a


std::runtime_error exception is thrown.

3. catch Block:

 The catch block is used to handle the exception thrown by


the throw statement.
 It specifies the type of exception it can handle—in this
case, const std::runtime_error&.
 The catch block captures the exception and allows the program to
handle it gracefully, instead of crashing.
 The captured exception object (e in this case) can be used to
get more information about the error.

4. e.what():

 The what() method is a member function of the


std::runtime_error class (inherited from std::exception).
 It returns a C-style string (const char*) that describes the exception,
which in this case is "Division by zero error".

12
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

4. Data Structures and Standard Template Library

4.1. Data structures:


As the data grows, the importance of using efficient data structures and
algorithms becomes paramount. Data structures are fundamental ways of
organizing and storing data so that it can be accessed and modified
efficiently. They are such containers that hold information in a specific
manner. In C++, some common data structures include: Arrays, Linked
Lists, Stacks, Queues, Trees, Graphs, and Hash Tables. The way we
organize data impacts how efficiently we can access and manipulate it.
The way the programmer organizes data it impacts how efficiently the
accessing and manipulating it. Choosing the right data structure is crucial
for writing efficient and effective programs. For example, if it needs to
quickly look up a value by a key, and it would use a different structure
than if it needs to maintain an ordered list. There for it is important to
comprehensively understand the data structures and that enable
programmers to consider the flowing points:

 Efficiency: Large datasets require efficient storage and retrieval.


Using the right data structure can significantly impact the
performance of the program. For example, using a map for key-
value pairs can provide faster lookups compared to a simple
array.
 Scalability: As data grows, the scalability of the chosen data
structures and algorithms becomes critical. Programmer need to
ensure that the solution can handle increasing amounts of data
without a significant drop in performance.
 Memory Management: Managing memory efficiently is crucial
when dealing with large datasets. C++ provides various
techniques to handle dynamic memory allocation and
deallocation, such as smart pointers, to prevent memory leaks
and fragmentation.
 Algorithm Complexity: Understanding the time and space
complexity of your algorithms helps in making informed
decisions. For example, a sorting algorithm with O(n log n)
complexity is more efficient for large datasets than one with
O(n^2) complexity.
 Parallelism: Leveraging parallel processing and multi-threading
can help in handling large datasets more efficiently. C++
provides libraries like OpenMP and tools like the C++ Standard
Library's concurrency features to aid in parallel processing.

4.2 Standard Template Library (STL):

The Standard Template Library (STL) is a powerful set of C++ template


classes to provide general-purpose classes and functions with templates
that implement many popular and commonly used algorithms and data
structures like vectors, lists, queues, and stack. Components of STL:
13
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

 Containers: Store collections of objects. Examples include vector,


list, deque, set, map, etc.

14
Software Engineering/OOP
Year 2. Semester 2, Sheet:01 Dr. Thaer F. Ali

 Algorithms: Functions that operate on containers. Examples


include sort, search, copy, swap, etc.
 Iterators: Objects used to traverse containers. Examples include
begin, end, next, prev, etc.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
std::vector<int> numbers = {1, 3, 5, 4, 2};

// Sort the vector


std::sort(numbers.begin(), numbers.end());

// Display the sorted vector


for (int num : numbers) {
std::cout << num << " ";
}

return 0;
}

In this example, we use the vector container is the structure to store a


sequence of integers and the sort is the algorithm to sort them in
ascending order.

15

You might also like