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

C++ Templates, Namespaces, and Exceptions

Uploaded by

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

C++ Templates, Namespaces, and Exceptions

Uploaded by

jiv555201
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Module 5:

Class template, Member function inclusion, Function template, Specialization,


Inheritance, Namespace. Concept of exception handling, Catch block, Nested try-catch
block, Condition expression in throw expression, Constructor & destructor, Runtime
standard exception. Standard library function, Input and output, IO stream class
hierarchy, Class ios, Other stream classes, Basics of file handling

1. Class Template
A class template in C++ is a blueprint for creating classes that can handle
different data types without rewriting the entire code.
It allows generic programming, meaning you can write a single class that works
with int, float, double, or even user-defined types.

Example:
#include <iostream>
using namespace std;

// Class Template Declaration


template <class T>
class Marks {
T sub1, sub2, sub3; // Marks of three subjects

public:
// Constructor to initialize marks
Marks(T s1, T s2, T s3) {
sub1 = s1;
sub2 = s2;
sub3 = s3;
}

// Function to calculate sum


T getSum() {
return sub1 + sub2 + sub3;
}

// Function to calculate average


float getAverage() {
return (sub1 + sub2 + sub3) / 3.0;
}

// Function to display results


void display() {
cout << "Marks: " << sub1 << ", " << sub2 << ", " << sub3 << endl;
cout << "Sum = " << getSum() << endl;
cout << "Average = " << getAverage() << endl;
}
};

// Main function
int main() {
// Using template for integer marks
Marks<int> m1(85, 90, 95);
cout << "--- Integer Marks ---" << endl;
[Link]();

// Using template for float marks


Marks<float> m2(78.5, 82.0, 91.5);
cout << "\n--- Float Marks ---" << endl;
[Link]();

return 0;
}
2. Member Function Inclusion
Member functions of a template class can be defined inside or outside the class definition.

Example:
template <class T>
class Box {
T value;
public:
Box(T v);
void display();
};

template <class T>


Box<T>::Box(T v) { value = v; }

template <class T>


void Box<T>::display() {
cout << 'Value: ' << value << endl;
};

3. Function Template
Function templates are another application of templates. Class templates were used to program
generic classes. Similarly, function templates are used to define generic functions to be able to
use a function independent of its data types for different data type combinations.
A Function Template in C++ is a single generic function that can work with different
data types (like int, float, double, etc.) without rewriting the same code multiple
times.
It enables generic programming — writing reusable functions that adapt to the type of
data they handle.
Example:
#include <iostream>
using namespace std;

// Function Template
template <class T>
T add(T a, T b) {
return a + b;
}

int main() {
cout << "Sum of integers: " << add(5, 10) << endl;
cout << "Sum of floats: " << add(2.5, 3.7) << endl;
cout << "Sum of doubles: " << add(12.35, 45.65) << endl;
return 0;
}

Difference Between Class Template and Function Template

Basis Class Template Function Template


A class template allows creating a A function template allows
Definition generic class that can handle creating a generic function that can
different data types. work with different data types.
Used when a class performs similar Used when a function performs the
Purpose
operations for different data types. same task for different data types.
Defined using template <class T> Defined using template <class
Keyword or template <typename T> before T> or template <typename T>
a class declaration. before a function definition.
Applies to all member functions
Scope Applies to a single function only.
and data members of the class.
The compiler generates a new class The compiler generates a new
Instantiation
for each data type used. function for each data type used.
Example template <class T> class Test template <class T> T add(T a,
Declaration { ... }; T b) { ... }
Test<int> obj1; Test<float>
Example Usage obj2; add(10, 20); add(2.5, 3.5);

Code Reuses entire class logic for Reuses function logic for multiple
Reusability multiple data types. data types.
Generally more complex as it may
Simpler — defines only one
Complexity contain multiple members and
function template.
methods.
When a class is designed to handle When a single operation is to be
When Used different data types (like Stack, applied on different data types (like
Array, Queue, etc.). add, swap, compare, etc.).

4. Template Specialization
Template specialization allows defining a specific version of a template for a particular data
type.

Example:
template <class T>
class Print {
public:
void show(T data) { cout << 'General template: ' << data << endl; }
};

template <>
class Print<char> {
public:
void show(char data) { cout << 'Character specialization: ' << data << endl; }
};

6. Namespace
1. Definition
A namespace in C++ is a container that groups related identifiers such as classes,
functions, objects, and variables under a single name to avoid name conflicts.
Namespaces help organize code logically and prevent ambiguity when two or more parts
of a program use the same name for different entities.

2. Need for Namespace


When programs become large or use multiple libraries, it is possible that:
● Two different libraries may contain functions or classes with the same name.
● The compiler may get confused about which one to use.
Namespaces solve this problem by defining unique scopes for identifiers.
3. Syntax of Namespace
namespace namespace_name {
// variable declarations
// function declarations
// class declarations
}
To access members:
namespace_name::member_name;

4. Example: Without and With Namespace


Without Namespace (Name Conflict)
#include <iostream>
using namespace std;

int value = 10;

int main() {
int value = 20; // local variable
cout << "Value = " << value << endl;
return 0;
}
Output:
Value = 20
Here, the global variable (10) is hidden by the local variable (20).

With Namespace
#include <iostream>
using namespace std;

// First namespace
namespace First {
int value = 10;
}

// Second namespace
namespace Second {
int value = 20;
}

int main() {
cout << "Value from First namespace: " << First::value << endl;
cout << "Value from Second namespace: " << Second::value << endl;
return 0;
}
Output:
Value from First namespace: 10
Value from Second namespace: 20
There is no conflict; both variables exist in their respective namespaces.
5. Using the using Keyword
To avoid writing the namespace name repeatedly, the using directive can be used.
#include <iostream>
using namespace std;

namespace Sample {
int num = 100;
void display() {
cout << "Number = " << num << endl;
}
}

int main() {
using namespace Sample; // Now we can directly use 'num' and
'display'
display();
cout << "Value of num: " << num << endl;
return 0;
}
Output:
Number = 100
Value of num: 100

6. Nested Namespace
A namespace can be defined inside another namespace.
#include <iostream>
using namespace std;

namespace Outer {
int x = 5;
namespace Inner {
int y = 10;
}
}

int main() {
cout << "Outer x = " << Outer::x << endl;
cout << "Inner y = " << Outer::Inner::y << endl;
return 0;
}
Output:
Outer x = 5
Inner y = 10
7. Anonymous (Unnamed) Namespace
If a namespace has no name, its contents are accessible only within the current file.
This is useful to prevent external access, similar to making global variables private to a
file.
#include <iostream>
using namespace std;

namespace {
int hidden = 42; // accessible only in this file
}

int main() {
cout << "Hidden value: " << hidden << endl;
return 0;
}

8. Advantages of Namespace

Advantage Description

Avoids Naming Prevents name clashes between identifiers in large programs or


Conflicts libraries.

Code Organization Groups logically related code together for better readability.

Modularity Makes it easy to separate code into modules.

Different modules can reuse the same function or class names


Reusability
without interference.

Limits access to variables and functions within specific


Control over Scope
namespaces.

Namespace avoids naming conflicts.

Example:
namespace first { int x = 10; }
namespace second { int x = 20; }
cout << first::x << ' ' << second::x;
7. Concept of Exception Handling
Used to handle runtime errors gracefully using try, throw, and catch.

Example:
try {
int a = 10, b = 0;
if (b == 0) throw 'Division by zero!';
}
catch (const char* msg) { cout << msg; }

1. Introduction
Exception Handling in C++ is a mechanism that allows a program to detect and handle
runtime errors in a controlled way without terminating abruptly.
It helps maintain the normal flow of execution even when unexpected conditions occur,
such as division by zero, file not found, invalid input, or memory allocation failure.
In simple terms, exception handling separates error detection from error handling,
making programs more robust and reliable.

2. Why Exception Handling Is Needed


In traditional error-handling methods (like using return codes or if-else statements), error
management becomes complicated, especially in large programs.
C++ provides a structured way to handle errors using exceptions so that programs can:
● Detect errors at runtime.
● Transfer control to a specific block that handles those errors.
● Continue or terminate gracefully after handling them.

3. Keywords Used in Exception Handling


C++ provides five key components for exception handling:
Keyword Description

try Block of code that may throw an exception.

catch Block that handles the exception thrown by try.

throw Used to signal (raise) an exception when an error occurs.

try- Together used to define the exception handling


catch mechanism.

... Catch-all handler to handle any type of exception.


Keyword Description

4. Basic Syntax
try {
// Code that may throw an exception
}
catch (type variable) {
// Code to handle the exception
}
If an exception occurs inside the try block, control is immediately transferred to the
corresponding catch block.

5. Example: Simple Exception Handling


#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;

try {
if (b == 0)
throw "Division by zero not allowed."; // throwing exception
cout << "Result: " << a / b << endl;
}
catch (const char *msg) {
cout << "Error: " << msg << endl; // handling exception
}

cout << "Program continues after exception handling." << endl;


return 0;
}
Output:
Enter two numbers: 10 0
Error: Division by zero not allowed.
Program continues after exception handling.

6. Types of Exception Handling in C++


C++ supports three main types of exception handling:
(a) Synchronous Exception Handling
Synchronous exceptions occur due to logical or runtime errors that the programmer can
predict and handle.
Example:
#include <iostream>
using namespace std;

int main() {
try {
int age = 15;
if (age < 18)
throw age;
cout << "Eligible to vote.";
}
catch (int x) {
cout << "Exception caught: Age " << x << " is less than 18." <<
endl;
}
return 0;
}
Output:
Exception caught: Age 15 is less than 18.
These are typical runtime exceptions like division by zero, invalid input, array index out
of range, etc.

(b) Asynchronous Exception Handling


Asynchronous exceptions occur due to external or unpredictable events that are not
directly caused by the program logic, such as hardware failure or operating system
interrupts.
C++ does not natively handle asynchronous exceptions, but certain systems or libraries
can manage such cases.
For general programming, asynchronous exception handling is rare in standard C++ and
is usually handled at the operating system or signal-handling level.

(c) Standard Exception Handling (Using std::exception Class)


C++ provides a hierarchy of standard exception classes defined in the <exception>
header.
These are part of the C++ Standard Library and are used to handle common runtime
errors like bad memory allocation or out-of-range access.
Common Standard Exceptions:
Exception Header Description

<exceptio
std::exception
n>
Base class for all exceptions

std::bad_alloc <new> Thrown by new when memory allocation fails


Exception Header Description

<typeinfo
std::bad_cast Thrown by dynamic_cast
>

<typeinfo
std::bad_typeid Thrown by typeid
>

std::out_of_rang <stdexcep Thrown when accessing out-of-range


e t> elements

std::runtime_err <stdexcep
or t>
Thrown for generic runtime errors

Example: Handling Standard Exception


#include <iostream>
#include <exception>
using namespace std;

int main() {
try {
int *arr = new int[100000000000]; // Large memory allocation
}
catch (bad_alloc &e) {
cout << "Standard Exception: " << [Link]() << endl;
}
return 0;
}
Output:
Standard Exception: bad allocation

7. Nested try-catch Blocks


C++ allows try-catch blocks inside another try block.
If an inner block does not handle an exception, it is passed to the outer block.
Example:
#include <iostream>
using namespace std;

int main() {
try {
try {
throw 20;
}
catch (int n) {
cout << "Inner catch: Exception " << n << " handled
partially." << endl;
throw; // rethrowing the exception
}
}
catch (int n) {
cout << "Outer catch: Exception " << n << " handled completely."
<< endl;
}
return 0;
}
Output:
Inner catch: Exception 20 handled partially.
Outer catch: Exception 20 handled completely.

8. Catch-All Handler
If the type of exception is unknown, a catch-all handler can be used with catch(...).

Example:
#include <iostream>
using namespace std;

int main() {
try {
throw 3.14;
}
catch (int) {
cout << "Integer exception caught." << endl;
}
catch (...) {
cout << "Unknown exception caught." << endl;
}
return 0;
}
Output:
Unknown exception caught.

9. Advantages of Exception Handling


1. Provides a clear and structured way to handle runtime errors.

2. Reduces code clutter compared to traditional error-checking methods.

3. Makes the program more reliable and maintainable.

4. Separates normal code logic from error-handling logic.

5. Supports catching specific and general exceptions.

10. Summary
Feature Description

Purpose To detect and handle runtime errors gracefully

Keywords try, catch, throw

Type of
Synchronous, Asynchronous, and Standard Exceptions
Exceptions

Exception transfers control from try block to the corresponding


Control Flow
catch block

Prevents abnormal program termination and maintains program


Advantage
stability

In Conclusion:
Exception Handling in C++ provides a structured mechanism to detect, signal, and handle
errors during program execution.
By using try, catch, and throw, programmers can isolate faulty code, handle runtime
errors efficiently, and ensure that the program continues or terminates gracefully without
crashing.

Catch Block & Nested Try-Catch


Catch block handles exceptions. Nested try-catch allows a try block inside another.

Example:
try {
try {
throw 10;
}
catch (int x) {
cout << 'Inner Catch';
throw;
}
}
catch (int x) {
cout << 'Outer Catch';
}

Condition Expression in Throw


throw can be used conditionally.
Example:
if (b == 0) throw 'Division by zero!';

Runtime Standard Exceptions


C++ standard exceptions in <stdexcept> include:
- runtime_error
- overflow_error
- out_of_range
- invalid_argument

12. Standard Library Functions


Predefined functions available in headers such as:
<iostream>, <cmath>, <cstring>, <algorithm>.

13. Input and Output


cin – standard input
cout – standard output
cerr – standard error
clog – logging output.

14. IO Stream Class Hierarchy


ios

├── istream
├── ostream
└── iostream

ifstream, ofstream, and fstream are derived from iostream.

15. Class ios


Base class for all I/O stream classes. Manages formatting, flags, and error states.

16. Other Stream Classes


istream – input
ostream – output
ifstream – file input
ofstream – file output
fstream – file input/output

*******************************************************************************************

You might also like