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

OOP Unit 5 Notes

Notes of oop unit 5,4,3

Uploaded by

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

OOP Unit 5 Notes

Notes of oop unit 5,4,3

Uploaded by

tardesakshi067
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 39
1[Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. Unit -V Exception Handling and Templates 1. Exception Handling 1.1 Fundamentals of Exceptional Handling Exception han ling is a mechanism used in C++ to deal with runtime errors (exeeptiOAS)hat may occur during program execution, Without exception handling, when an @tror occurs, the program terminates abruptly, which can lead to data loss or an inconsistent stateException handling helps manage such errors by allowing the programjt6 hatidle theinpgracefully and recover without terminating immediately. Common Examples of Exceptions in C++ (C++ exceptions are triggered when an effor or unexpected condition occurs during program execution. Below are four common examples of exceptions 1. Division by Zero + Cause: Occurs When a program, attempts to divide a mumber by zero, which is ‘mathematically undefined. + Explanation:“this typicallyileads to a runtime error or undefined behavior. + Handling: Use a conditional check or throw an exception to handle the error. 2. Array Out-of-Bounds Access +_¢€ause! Happens when a program tries to access an array index that is outside its valid range. + Explanation: This can corrupt memory or cause segmentation fault. + Handling: Use bounds checking or throw an exception if an invalid index is accessed, le Not Found + Cause: Occurs when a program tries to open or read a file that does not exist or is inaccessible. 21Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. + Explanation: The file handling functions fail, and the program cannot proceed, + Handling: Check if the file exists before accessing it, or use exception handling to ‘manage the error, 4. Invalid Type Conversion ‘+ Cause: Happens when a program attempts to convert between incompatible types, such. as converting a string to an integer. + Explanation: May result in undefined behavior or runtime errors. + Handling: Validate the input or throw an exception for invalidjeonversioits. For example: int c= a/b; // if b= @, this will generate a runtime error Need for Exception Handling Without exception handling, errors cause the program to fétminate, potentially leading to: + Data loss: If the program crashes before saving user input. ‘+ Inconsistent state: Dataziiight be left in an invalid state, especially in commercial applications, + Financial loss: £9 progtans involving transactions or sensitive data, an error can cause significant problems. How to Handle Exceptions C+ provides three common ways to handle exceptions; 1.4 Remedial. Action: The program tries to fix the issue and continues execution 2 Retry: The program displays the error and prompts the user to correct the mistake, 3. Terminate: The program shows an error message and stops. C++ Exception Handling Keywords C+ uses three keywords for exception handling: 1. try: Defines a block of code that may generate an exception. 31Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. 2. eattch: Catches and handles the exception thrown by the try block. 3, throw: Used to throw an exception when an error occurs. Structure of try-cateh A basic try-catch block looks like this: try { // Code that may generate an exception + catch (Type variable) { // Code to handle the exception + + The try block contains code that may throw an,exeeption + The catch block catches the throwsiékteption and handles it. + Type is the data type of the exception being thrown(eg., int, string). Key Points: ‘+ Aprogram can haye multiple catch blocks to handle different types of exceptions. + Ifno exception oceutithe catch bl0ek is skipped. + fan exceptiofis thrown, the control jumps directly to the catch block, and the rest of the try bloehais skipped. «he data type oF he thrown exception must match the type in the catch block to ensure proper handlings Exaile: Program to handle exception using class type exception, #include) using namespace std; // Define a custom exception class class MyException { public: // Constructor to display an error message alrace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. MyException(const char* msg) { errortlessage = msg; // Function to get the error message const char* getErrormessage() { return errorMessage; private: const char* errorMessage; int main() { try { i mulate an error by €hrowing @) custom exception throw MyException(s"Custom exception occurred!"); } catch (Myexception& e) { // Catch the custg Sception and display the error message coutye< "Caight exception: " << e.getErrorMessage() << endl; peturn @; + 1.2 Simple Exception Handling - Example of Exception Handling #include using namespace std; int divide(int a, int b) { 51Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. if (b == 0) { throw "Division by zero error"; // Throw an exception if // divisor is zero + return a / bj int main() { int numerator, denominator; cout << “Enter numeratoi cin >> numerator; cout << “Enter denominator: cin >> denominator; try { int result = divide(numerator, denominator); 11 attemp@divi Sion cout << "Result: " << result << endl; } catch (const chan* msg) { // Catch and handle the exception cout << "Exception caught: " << msg << endl; } néturn a; + Sample Oittput: Case 2: Division by zero Case 1: Valid division Enter numerator: 18 Enter numerator: 10 Enter denominator: @ Enter denominator: 2 Exception caught: Division by zero error Result: 6lPace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. 1.3 Multiple Catching In C++, exception handling is managed using the keywords try, catch, and throw. This allows a program to detect and handle errors (exceptions) gracefully during execution, + try block: This contains the code that might throw an exception. + catch block: This handles the exception. Multiple catch blocks can be used to handle different types of exceptions separately. + throw keyword: This is used to throw an exception from the try block ultiple eatch Blocks When an exception occurs in the try block, the control is transfetfed to the cotresponding catch block that matches the type of the thrown exception. If no exception/ocelirs, none of the catch blocks are executed. Multiple catch blocks allowltie pfSgrimmer to handle different types of exceptions separately, based on the type offéXeeption thrown. Each catch block handles a specific type Of exception, and Only the first matching catch block is executed. After the first matching block executes, the Amaining blocks are skipped. ‘Syntax of Multiple Catch Blocks try { // Code that qidy geherate.exceptions + catch (Type variable), { /hCode to handle exception of type Typel } catch (Type2\yariable) { Pode to handle exception of type Type2 + catch (Type_n variable) { // Code to handle exception of type Type_n + Example: Consider a program where we perform division and subtraction, and exceptions are thrown in specific conditions. 7IPage © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. #include using namespace std; int main() { int e1, sub; float a, b, div, e; try { cout << “Enter two numbers: "5 cin >> a >> b; // Throw exception if second number is z ide by zero) if (b == @) throw e; div = a/b; cout << "\nDivision is: 7/ Throw @eptioflit fipst number is smaller than the second number if (a using namespace std; int main() { int e1, sub; float a, b, div, @; try ( cout << “Enter two numbers: "; cit\>> a >> b; %/ Throw exception if second number is zero (divide by zero) if (b == @) throw e; div = a/b; cout << "\nDivision is: " << div; tl Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. + // Throw exception if second number is greater if (a using namespace std; int main() { int a; try { // outer try block try { // Inner try block cout << “Enter a number: \"5 cin >> a3 if (a == 1) throw 53 // Thrdlan inteBer exception cout << “Try ends, a = << endl; + e@ catch (int Tnn@p catch block cour "Inner catch, exception = " << ex << endl; ‘OWS jf Rethrow the exception } i yt 8X) { // Outer catch block cout << "Outer catch, exception = " << ex << endl; + cout << "Program ends\n"; return @; + Explanation Case 1: Ifa [Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. ‘+ An exception is thrown in the inner block, + The inner catch block handles it partially and rethrows it us + The outer catch block then handles the rethrown exception. Case 2: Ifa 1 + No exception is thrown, so the inner block executes successfully, and no catch blocks are triggered. 1.6 Exception Specification Exception specification in C++ is a mechanism that limits the types of exception8}a function can throw. It serves might be thrown. 'S @ guarantee to the caller of the function Spevifying Which exceptions Syntax void function_name() throw (type1, type2, + typel, type2, +: List of exception types the function is allowed to throw. + throw(): Indicates that thefunction will not throw any exceptions, Key Points 1, Ifa function throws an eXceptionithat is not in its exception specification, the runtime calls unexpected() A funétion withino exéeption specification (throw( )) guarantees it will not throw any. ‘exeeptions, 3,A funtion without any exception specification can throw exceptions of any type. 4. Bxception specification is enforced only at runtime, meaning the compiler does not prevent exceptions outside the specified list. Rules for Nested Function Calls ‘+ Ifa function calls another function with a broader exception specification (i.e., one that allows more exception types), any exceptions not in the outer funetion’s specification ‘must be handled by the outer function. 13 Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. + Failing to handle such exceptions results in a call to unexpected().. Example #include using namespace std; void subFunction() throw (int) { throw 1@; // Throws an int exception void outerFunction() throw (int) { try { subFunction(); // Calls a } catch (int e) { cout << "Caught exce ‘specification } + e@ int main() { try { outerFunctiton(); { ndled exception!" << endl; Explanation 1, The subFunction and outerFunction both specify that they can throw’ int exceptions, 2. ‘The subFunction throws an exception, which is caught by the outerFunction. i lPace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. 3. If an exception outside the specified types (e.g., Float) is thrown, unexpected() would be called. 1.7 User Defined Exceptions In C++, we can create custom exception classes to handle specific error conditions in a program. These are called user-defined exceptions and are typically derived from the standard exception class. Key Features 1, Custom Class: Define a 18s for the exception, usually derived frm the built-in exception class, ‘Members: The class can include data members, constructorsjland metiber functions for custom error handling or displaying error messages. ‘Throwing an Exception: When an efféPcondition occurgan object of the user-defined exception class is created and thrown using the thow keyword 4, Catching the Exception: To handle\the exceptidh, define a catch block that matches the type of the user-defined class. Example: The followit@'program throws and handles a user-defined exception if the second ‘number is smaller than the fit, #include using namespaée std; // UserMieFinkt exfeption class derived from ‘exception class) DemoEXpt : public exception { publ ies void ’showerr() { cout << "Demo Error Occurred: Second number is not smaller than the first.\n"; } bb int main() { Bl Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. int a, b; cout << "Enter two numbers: "; cin >> a >> b; try { if (a header. This function alloWs you fo set a custom termination handler that will execute instead of the default terminate() function. Example: Custom Termination Handler The following program demonstrates howto set a custom handler for unexpected exceptions #include #tinclude using namespace)std; K/ CuspOMterMygPion handler void) myhandler() { cout << “Inside custom terminate handler\n"; abor€()3 // Aborts the program int main() { // Set the custom termination handler set_terminate(myhandler); Wrage © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. try { cout << “Inside try block\n"; throw 100; // Throws an integer exception + catch (char a) { // This block doesn't catch the int exception cout << “Inside catch block\n"; } return @; + Explanation 1. Custom Handler: © The myhandler function is defined to replace thé défault termination behavior. © It displays a message and calls abot () 2. Uncaught Exception: © The try block throws an integer exceptioin(throw 100), © The catch blockiis desighed to handle a char exception, so it doesn’t match the thrown, exception, 3. Result: ©The program Galls tetminate( ), which invokes the custom handler (myhandler) © Théprogram outpute'a message from myhandler and aborts. 1.9 Constructor and Exception Handling In C+ leonstructors can be used in exception handling to initialize and store data related to the error condition, When creating a user-defined exception class, constructors are often used to pass and store error-specific data that can later be displayed or used in the error-handling, process. Key Points 1. User-Defined Except Awl Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. © Typically derived from the built-in exception class © Contains data members, constructors, and functions for error handling Parameterized Constructor: © Used to pass and store invalid values or details about the error condition when the exception object is created. 3. Throwing the Exception: © An object of the user-defined exception class is created with the errétspecifie data and then thrown using the throw keyword. 4. Catehing the Exception: © The catch block defines an object of theuser-defined class fo handle the exception and. can access the stored error data, Example #include #include using namespace std; // User-defined efpeptitn class class Demo€xpt : public exéeption { int vif/v23%j/ Data members to store invalid values publi G7 consyctor to collect error-specific data DefioExpt(int a, int b) { vi = a3 v2 = b5 // Function to display error details void ShowErr() { 19] Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. cout << “Error: Invalid values - * << vi << " and " << v2 << endl; } int main() { int a, bj cout << "Enter two numbers cin >> a >> b; try { if (a using namespace std; class Test { int ids public: Test(int id) : id(id) { cout << "Constructor of object " << id << endl; + Test() { cout << "Destructor of obj « ena // Unconmenting the bel Hinate() // throw runtime_erronfexceptioM ctor"); } be int main() { ° try { Test t1 Qi); // autgpatic object 1 Te Ny Automatic object 2 cout owing an exception...\n"; Ime_error(“Error occurred!"); h (runtime_error &e) { ut << "Caught exception: " << e.what() << endl; } cout << "Program ends\n"; return @; 2zlIPove © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. Explanation 1. Construetor Calls: © Objects t1 and t2 are created in the try block, and their constructors are called 2. Stack Unwinding: © When an exception is thrown, control moves to the catch block, and the destructors of t2 and t1 are called in reverse order of their creation. 3. Exception in Destructor: © Ifa destructor throws an exception and it is not handled, the progam will férminate by calling terminate(). 1.11 Exception And Inheritance In C+, it is possible to throw and catchyelass objects as eXceptions. When dealing with inheritance in exceptions, special rules apply due to the flationship between base and derived classes. Key Points 1. Catching Base and Derived Classes: © Ifa derived classi thrawn as an exception, it can be caught by a catch block for either the derived clas or its baselelass. © A catchyblock\for the Gerived class takes precedence over a base class block. Order of Catch Blocks: je. Rule: The catch block for the derived class must appear before the block for the base class. © I the?base class catch block is placed first, the derived class catch block will never be executed because the base class block matches all derived types. 3. Compiler Behavior: © The C++ compiler might issue a warning if the base class cateh block precedes the derived class block, but the code will still compile. © However, this can lead to unexpected behavior. 231 Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. Example #include using namespace std; class Base {}; class Derived : public Base {}; int main() { Derived d; // Object of derived class try { throw d; // Throwing an object of denfved Blass + catch (Derived &d) { // Catchedertad clad First cout << "Caught Derived Exception! << endl; } catch (Base &) { // Catch baSByclasé cout << "Caught BaSe Exception” << endl; } return @; + Explanation 1. Throwing Derived Class: © The abject d of the Derived class is thrown, 2. Order of Catch Blocks: © The catch block for Derived is matched and executed first. © Ifthe catch block for Base was placed first, it would catch all derived class objects, and the Derived block would never be executed. 2. Templates 2|Pove © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. ‘Templates are a fundamental feature in C++ that allow the creation of generic code. They enable the definition of functions and classes that can operate with different data types without requiring separate implementations for each type. What Are Templates? + When defining a function or a ch 3s, we usually specify the data types of the variables to match the type of data and operations required. ‘+ However, sometimes the same logic can be applied to different types of data, © Example: Swapping two values, whether int, Float, or char, involvesthe same steps. + Using Generic Programming, a single fu tion or class can be designed to work’with any type of data. + Templates provide a way to achieve "Same logic, différent data types." Gen Programming with Templates Definition: A programming style where one algorithm is dé8igned to perform specific tasks, independent of the data type it operates on. + The data type is specified fater, during the function call or class instantiation. Advantages of Templates 1, Code Reusability: Write Ohe code block and use it for various data types. 2, Efficienfey Avoid cade duplication for similar operations on different data types. Flexibility! Handle, primitive types (int, float, etc.), arrays, pointers, or even user- defined objects! 4. Scalal ity: Easily extend functionality to new data types by reusing the same logic ‘The Power of Templates + Templates enable programmers to write generalized and reusable code. + They are particularly useful for data structures and algorithms, such as sorting, searching, and stacks, which can work with different types of data 2.1 Generic Programming 251Pove © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. Gene Programming is a programming paradigm where the algorithm is designed to perform a specific task without depending on a particular data type. Instead, the same algorithm can operate on different data types, with the type being specified at runtime, In simpler terms, it's about writing algorithms and functions that can handle any data type without changing the underlying code for each data type. This allows the code to be more flexible, reusable, and maintainable. Core Concept of Generic Programming + The same algorithm works for different data types. +The data type is not hardcoded into the algorithm or function but is defied during function or class invocation (at runtime), ‘+ Types are generic, meaning we use placeholderssfor types (usually T or typename), and the actual type is specified when the funtion or class is called. Gen Programming in C++ with Templates In C++, templates provide the mechanism)for implemnting generic programming. They allow you to create generic functions and classeSithaffean work with any data type. + Template Function: Allows you.to write a funetion that ean work with any data type. + Template Cla cIAllows you to create a class that can handle any data type. ‘The template type is used to define Variables within the function or class, and the specitie data type is providéd whehnyou call. the function or instantiate the class. 2.2 Function Template ‘Afunetion template allows you to define a generic function that can work with any data type. Instead)of specifying a particular data type for function parameters and return types, you can define a template that allows the function to accept different types of data, such as int, float, double, or even user-defined types What is a Function Template? A function template is a function that can operate with any data type. It is defined using the template keyword and a placeholder for the data type, which is typically represented by T or another generic name, 261Poce © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. ‘Syntax for Defining a Function Template: template ReturnType FunctionName(Parameters) { Function logic ‘template: The keyword used to define a template function. €lass TypeName: This is the placeholder for the data type that will be used.in the function. You can also use typename instead of ss. The type namewill be specified when the funetion is called. ReturnType: The return type of the function, which will be Replaced with the template type during function call, FunctionName: The name of the function being defied. Parameters: The function's parameters, which caibe of the template type. When you call a template function, you provide the actual data type for TypeName in the form of Funct ionName (arguments)s Benefits of Function Templates: 1 Code Reusabiliff: You}can write one function that works with multiple data types, avoiding code duplication. Flexibility: The same}function can work with different types of data, such as integers, oats, and giser-défined types, with no additional code changes, ‘Type Safety: The compiler ensures that the function is used with compatible data types. Ma ability: Having a single function template makes the code easier to maintain. andlextend, Example 1: Function Template for Sum of Two Values #include using namespace std; template 21 Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. TempType Add(Temptype a, TempType b) { TempType cs c a+b; return c; int main() { + int p= 4, q = 3, float x = 3.4, y= 1.2, 23 // Call function with int type r= Addcint>(p, 9); cout << "Sum of ints << nce endl J/ Call function with floaetype 2 = Add(x, y); cout << "Sum of floats,= "<< z «endl; return @; Explanations © The function! Addis a template function that can add two values of any data type (TempType). ‘3\| When the function is called in the main() function, the data type (int or float) is Exa Hin usii spécitied, and the compiler generates the appropriate function, Add(p, q) adds two integers, and Add(x, y) adds two floating-point numbers, ple 2: Function Template for Finding the Minimum Value in an Array clude ng namespace std; 21 Poce © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. // Function template to find the minimum value in an array template T findMin(T arr[], int size) { T minVal = arr[@]; // Assume the first element is the minimum for (int i = 1; i < size; ++i) { if (arr[i] < minval) { minVal = arr[i]; } return minval3 int main() { // Example with integers int intarr[] = {10, 20, 5, 8))15}; int size = sizeof(intarr) / sizeoF(intarr[@]); cout << "Minifiim in| integer array: " << findMin(intarr, size) << endl; // Example with floatiR-point numbers float floatAnr[] 2{2.5, 1.2, 3.8, 0.9, 4.5} size = sizeof(floatarr) / sizeof(floatarr[@]); cout & "Miliimum in float array: " << findMin(floatarr, size) << endl return 0; + + Explanation © The Min function is a template function that finds the smallest element in an array. It works with both int and float types because the data type is specified at the time of function call (Mincint> for integers, Min for floats). 2 [Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act © Depending on the user's choice (opt, the function either works with an array of integers, or floats to find the smallest number. 2.3 Overloading Function Templates Function overloading is a form of polymorphism in C++, where multiple functions can have the same name but differ in their parameter types or the number of parameters. This allows the programmer to define several functions that perform similar operations but on different types of data, When using function templates, overloading can also be applied to define a function template that works with different data types. How Does Overloading Work with Templates? Ifyou have a normal fun mn (non-template) and a template funetion With the same name, the compiler will use the normal function for exactimatches Gf data f¥pes. If there is no exact match, the template function will be used! For example: #include using namespace std; void add(int a, int b) { cout << "Sum of int = "<< (a +b) << endl; template void add(Temptype a, TempType b) { Temprype ¢3 ca at; cout << "Sum << € << endl; int main() { int x = 5, y = 10; 301 Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. float p = 2.5f, q = 3.5%; add(x, y)5 // Calls the normal function (add(int, int)) add(p, 4)3 // Calls the template function (add) return @; + + Explanation: © The function add(int, int) is a regular function, so ityill be wed whe the arguments are of type int. © For other types like float, the template fumetion adddis used. 2.3 Class Template and Non-Type Parameters, In. C++, elass templates are used when we need to createa class that can operate on a variety of data types. A class template allows us t@ define a class whete the data type is pecified at the time of object creation (instantiation), makinglthe class flexible and reusable for different types of data, Class templates are idealyfar generic programming, as they allow the same class to work with different data types without duplicating the code. Class Template Syntax The basic syntax for defining a classitemplate is: template <€lass TypeNatte> class ChassName { 1p neers i, NenberFunctions + template : This part defines a template class. The TypeName is a placeholder for a data type that will be specified later when an object of the class is created, ‘+ class ClassName: This defines the name of the class template, The class can now use the TypeName in its data members and member functions to allow flexibility in the types of data it can work with, BilPoge © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. Object Creation for Class Template When creating an object of a class template, we specify the actual data type to be used. The compiler then replaces the template with the specified data type, generating a new class that ‘operates on that data type, ‘The syntax for creating an object of a class template is: ClassName object_name; + DataType: This is the type of data (such as int, float, char, etc.) thatthe classitemplate will use. + object_name: This is the name of the object created fromthe clasStemplate. Class Template using multiple parameters In C++, a class template can accept multiple template parameters, allowing you to create a class that works with more than one data typedThis feature enables yOu to design classes that can operate on various types of data and support mul le operations that involve these types. ‘Syntax of Class Template with Multiple Parameters: template class ClassName { // Class defiggrion + TypeVand Type? ate placeholders for data types that will be defined when creating Objects of the class, + You ein haveltiore than two template parameters as needed. Example Program Using Class Template with Multiple Parameters, #include using namespace std; // Class template accepting two parameters template class Adder { 321 Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. private: Typel first; // First number Type2 second; // Second number public: // Constructor to initialize the numbers Adder(Type1 f, Type2 s) : first(F), second(s) {} 7/ Method to add the two numbers and return the resul Typet add() { return first + second; int main() { // Creating objects of Adder@lass with int and float types Addercint, float> addert(5, 3.5); cout << "Sum int + float): " << addert.add() << endl; // Creating jects er class with double and int types Adder > adder2(5.5, 7); jouble + int): " << adder2.add() << endl; ng objects of Adder class with float and double types fer adder3(2.5f, 4.5)5 cout)<< "Sum (float + double): " << adder3.add() << endl; return 5 + This C+ program demonstrates a elass template with multiple parameters. The Adder class takes two data types as template parameters and adds two numbers of those types. 331 Poge © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. + The Adder class has a constructor to initialize the two numbers and a method add() to perform the addition. + Inmain(), three Adder objects are created with different types (e.g., int and float, double and int), + The result of the addition is printed for each pair of types. Non-Type Parameters in Class Templates In addition to type parameters, non-type parameters can also be used in class templates. These are values that are passed as arguments to the template. Non-type parameie®.are typi¢ally constant expressions, such as integers, pointers, or other compile-time constant valties. Syntax for non-type parameters: template class ClassName { // Data members and memberfFunctions ‘+ int Size is a non-type parameter, It repréSents/a constant value that must be specified when the class iginstantiated, + Non-type parametersiare often used when you need to define sizes, limits, or other constant values for a classitemplate. 2.4 Template anid Friend Generic Function A template friend function combines the concepts of templates and friend functions. You can declare a friend funtion as a template function to allow it to work with any data type while stithhaving acce§s to the private members of a class. To do thigp 1, The class defines the friend fun: 2. The friend function is also defined as a template, allowing it to work with various data types. Syntax for a Template Friend Function: template 34] Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. class ClassName { // Declare the template friend function friend ReturnType FriendFunctionName(ClassName&) ; // Define the friend function outside the class template ReturnType FriendFunctionName(ClassName& obj) { 7/ Function implementation + Example of Template and Friend Function: #include using namespace std; template class Box { private: T tength; XX ne oO r unction declaration as template Bo; fi f righd T getArea(BoxcT>& b); // Friend template function oF // Friend template function definition ‘template T getArea(Box& b) { return b.length * b.length; // Access private member ‘length’ of Box 351Poge © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. int main() { Box intBox(5); Box doubleBox(3.5); cout << “Area of int box: " << getArea(intBox) << endl} cout << "Area of double box: " << getArea(doubleBox) < 361 Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. FunctionOrClassDefinition; Example: template void Swap(tempType& a, tempType& b) { temptype t3 tea; a=; ‘+ typename declares tempType as a generic type. = You e: also use the class keywordsinsteath of typename. ‘There is no functional difference between using class and typenane inithis conteXt. Both are used to specify the type parameter for the template, Second Use: Indicating a Type Name in Nested Classes ‘The typename keywords also used to inform the compiler that a name is a type name rather than an object or variable. This is particularly important in cases where a name is part of a template class or when fecessingypestiésted within templates. Example: template class MyClass { publite: ‘typename temptype: :Name somedbject; ub Here: + typename tempType: :Name tells the compiler that tempType: : Name is a type (not an object) and should be treated as such, + This is necessary because the compiler might not automatically reco; due to its dependency on the template parameter. 371Pege © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. 2. export Keyword The export keyword was introduced in earlier versions of C-++ to help with separating the declaration and definition of template classes or functions. It allows you to declare a template in one file and then define it in another file, promoting reusability and cleaner code. Purpose: + The export keyword enables the template to be used across multiple translation units (source files) without requiring the full definition in each file. «Its used to make templates reusable by declaring them in a header fil@while keeping their definitions in a source file However, the export keyword is not widely supported in modern C+ eompilets and has been deprecated. Most modern C+ compilers do n6t,implement it dué to its e8mplexity and lack of widespread use. Today, templates are typieally Weelared ‘aiid, defifed in header files, and export is rarely used in practice. Example (conceptual, as export is not commonly supported): export template void Swap(T& a, T&b) { ([/ Define the template function with “export Tt tea a=b; b= ty } inthis example; + (export allows the template definition in one file while still being usable in other files thatjinclude the header with the declaration. + However, this syntax is mostly outdated and not widely supported. 381 Poce © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. 2.6 Difference between Overloaded Functions and Function Templates Aspect Overloaded Function Fanetion Template Definition ‘A feature in C++ where multiple | A generic function that can work with functions with the same name but | any datatype, defined using different parameter lists are | templates. defined. Flexibility Works with specific data types | Works with multiple datalfypes using defined in individual funetion | a single generic definition, definitions, Number of | Requires separate function | Requires only oie generi@pfunction Functions definitions for each data type. | definitiof/forimultipl@data types. Code Limited, as each datatype | High, a8 a sipglefunction can handle Reusability | requires a separate function. frultiple data types. Implementation | Handled by the progfaifimer, [Handled Wby the compiler, which with manual definitions for each type. gentrates type-specific functions from the template at compile time. Performance Usage Slightly faster, as the functionpis: specifically défigned for a single data type, Best) >for situations where funetions need Specific logic for Gifferentdata types. May introduce minor overhead during compilation, as the compiler generates code for each used data type. Best for scenarios where the same logic can be applied to multiple data types. Synitaiy No We of template keyword Defined with the template or templatectypenane T> keyword. 391 Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. 2.7 Difference between Class Template and Function Template Aspect | Class Template Function Template Definition | A template used to define a class that | A template used to define a function can work with multiple data types. | that can work with multiple data types. Purpose | Enables the creation of classes that | Enables the creation of funetions that handle generic types, such as data | can perform the same operation on structures or utility classes ferent data types. Scope of | Provides a blueprint for creating | Provides a mechanism forgereating Use objects that operate on different data types. type-independent functions. Complexity Usually more complex as it deals with multiple member funetions and Simplengas Wy focuseSson a single operation or logic} variables, Usage Used when multiple gmethber | Lised for Single operations like sorting, funetions or data members depend on | seafehing, or arithmetic where only the generic type. thé logic depends on the type. Syntax | Defined using tenplatecclass\yi>) Defined using template or templatectypename T> before | or templatectypename T> before the class definition? the function definition. Example | Often sed fOy implement data | Often used for algorithms or utilities Usage structures (e.g., vectOi stack, queue). | (e.g., addition, swapping values). Object |JREqUies creating objects of the class | Does not require an object; directly Creation | by gSpetifying the data type at| calls the function with the required runtimes data type.

You might also like