0% found this document useful (0 votes)
53 views35 pages

C++ Second Internal Study Material

The document discusses various object-oriented programming concepts in C++ including: 1. Inheritance allows a derived class to inherit attributes and behaviors from a base class. There are different types of inheritance in C++ including single, multiple, hierarchical, multilevel, and hybrid inheritance. 2. Constructors and destructors are special types of methods used to initialize and cleanup objects. Constructors are invoked during object creation and destructors are invoked during object destruction. 3. this is a keyword that refers to the current class instance and is used to access members of the current object. 4. Virtual functions allow functions to be overridden in derived classes and ensure dynamic binding occurs at runtime.

Uploaded by

P Rakini
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)
53 views35 pages

C++ Second Internal Study Material

The document discusses various object-oriented programming concepts in C++ including: 1. Inheritance allows a derived class to inherit attributes and behaviors from a base class. There are different types of inheritance in C++ including single, multiple, hierarchical, multilevel, and hybrid inheritance. 2. Constructors and destructors are special types of methods used to initialize and cleanup objects. Constructors are invoked during object creation and destructors are invoked during object destruction. 3. this is a keyword that refers to the current class instance and is used to access members of the current object. 4. Virtual functions allow functions to be overridden in derived classes and ensure dynamic binding occurs at runtime.

Uploaded by

P Rakini
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
You are on page 1/ 35

1.

Define- Inheritance:

inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically

Types Of Inheritance

C++ supports five types of inheritance:

o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance

Derived Classes

A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

1. class derived_class_name :: visibility-mode base_class_name  
2. {  
3.     // body of the derived class.  
4. }  

Where,
derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base class are publicly
inherited or privately inherited. It can be public or private.

C++ Single Inheritance

Single inheritance is defined as the inheritance in which a derived class is inherited from the only one
base class.

Where 'A' is the base class, and 'B' is the derived class.

Example Program:

#include <iostream>  
using namespace std;  
 class Account {  
   public:  
   float salary = 60000;   
 };  
   class Programmer: public Account {  
   public:  
   float bonus = 5000;    
   };       
int main(void) {  
     Programmer p1;  
     cout<<"Salary: "<<p1.salary<<endl;    
     cout<<"Bonus: "<<p1.bonus<<endl;    
    return 0;  
}  

Output:

Salary: 60000
Bonus: 5000
Visibility modes can be classified into three categories:

o Public: When the member is declared as public, it is accessible to all the functions of the program.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own class as well
as the class immediately derived from it.

C++ Multiple Inheritance

Multiple inheritance is the process of deriving a new class that inherits the attributes from two or
more classes.

Syntax of the Derived class:

class D : visibility B-1, visibility B-2, ?  
{  
    // Body of the class;  
}   
Example Program:

#include <iostream>  
using namespace std;  
class A  
{  
    protected:  
     int a;  
    public:  
    void get_a(int n)  
    {  
        a = n;  
    }  
};  
  class B  
{  
    protected:  
    int b;  
    public:  
    void get_b(int n)  
    {  
        b = n;  
    }  
};  
class C : public A,public B  
{  
   public:  
    void display()  
    {  
        std::cout << "The value of a is : " <<a<< std::endl;  
        std::cout << "The value of b is : " <<b<< std::endl;  
        cout<<"Addition of a and b is : "<<a+b;  
    }  
};  
int main()  
{  
   C c;  
   c.get_a(10);  
   c.get_b(20);  
   c.display();  
  
    return 0;  
}  
C++ Multilevel Inheritance

Multilevel inheritance is a process of deriving a class from another derived class.

C++ Multi Level Inheritance Example

When one class inherits another class which is further inherited by another class, it is known as multi
level inheritance in C++. Inheritance is transitive so the last derived class acquires all the members of
all its base classes.

#include <iostream>  
using namespace std;  
 class Animal {  
   public:  
 void eat() {   
    cout<<"Eating..."<<endl;   
 }    
   };  
   class Dog: public Animal   
   {    
       public:  
     void bark(){  
    cout<<"Barking..."<<endl;   
     } };   
   class BabyDog: public Dog   
   {    
       public:  
     void weep() {  
    cout<<"Weeping...";   
     } };   
int main(void) {  
    BabyDog d1;  
    d1.eat();  
    d1.bark();  
     d1.weep();  
     return 0;  
}  

C++ Hybrid Inheritance

Hybrid inheritance is a combination of more than one type of inheritance.

#include <iostream>  
using namespace std;  
class A  
{  
    protected:  
    int a;  
    public:  
    void get_a()  
    {  
       std::cout << "Enter the value of 'a' : " << std::endl;  
       cin>>a;  
    }  
};  
  
class B : public A   
{  
    protected:  
    int b;  
    public:  
    void get_b()  
    {  
        std::cout << "Enter the value of 'b' : " << std::endl;  
       cin>>b;  
    }  
};  
class C   
{  
    protected:  
    int c;  
    public:  
    void get_c()  
    {  
        std::cout << "Enter the value of c is : " << std::endl;  
        cin>>c;  
    }  
};  
  
class D : public B, public C  
{  
    protected:  
    int d;  
    public:  
    void mul()  
    {  
         get_a();  
         get_b();  
         get_c();  
         std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;  
    }  
};  
int main()  
{  
    D d;  
    d.mul();  
    return 0;  
}  
C++ Hierarchical Inheritance

Hierarchical inheritance is defined as the process of deriving more than one class from a base class.

Syntax of Hierarchical inheritance:

class A  
{  
    // body of the class A.  
}    
class B : public A   
{  
    // body of class B.  
}  
class C : public A  
{  
    // body of class C.  
}   
class D : public A  
{  
    // body of class D.  
}   
C++ Constructor

 Constructor is a special method which is invoked automatically at the time of object creation.

 It is used to initialize the data members of new object generally.

 The constructor in C++ has the same name as class or structure.

Types of Constructors

C++ Default Constructor

 Default constructor is the constructor which doesn't take any argument.


 It has no parameter.

Syntax:

class_name()
{
// constructor Definition
}

For example:

class Cube
{
public:
int side;
Cube()
{
side = 10;
}
};
int main()
{
Cube c;
cout << c.side;
}

C++ Parameterized Constructor

A constructor which has parameters is called parameterized constructor.

It is used to provide different values to distinct objects.

Syntax:

class_name(var1, var2.... var n)


{
// constructor Definition
}

Example:

class Cube
{
public:
int side;
Cube(int x)
{
side=x;
}
};

int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}

COPY Constructor

 Copy Constructor is a type of constructor which is used to create a copy of an already existing
object of a class type.
 It is usually of the form X (X&), where X is the class name.
 The compiler provides a default Copy Constructor to all the classes.

Syntax:

Classname(const classname & objectname)


{
....
}
Example Program:

#include<iostream>
using namespace std;
class Samplecopyconstructor
{
private:
int x, y; //data members

public:
Samplecopyconstructor(int x1, int y1)
{
x = x1;
y = y1;
}

/* Copy constructor */
Samplecopyconstructor (const Samplecopyconstructor &sam)
{
x = sam.x;
y = sam.y;
}

void display()
{
cout<<x<<" "<<y<<endl;
}
};
/* main function */
int main()
{
Samplecopyconstructor obj1(10, 15); // Normal constructor
Samplecopyconstructor obj2 = obj1; // Copy constructor
cout<<"Normal constructor : ";
obj1.display();
cout<<"Copy constructor : ";
obj2.display();
return 0;
}

OUTPUT:

Normal constructor : 10 15
Copy constructor : 10 15
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only
once in a class. Like constructors, it is invoked automatically.

A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde
sign (~).

C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.

Example Program:
#include <iostream>  
using namespace std;  
class Employee  
 {  
   public:  
        Employee()    
        {    
            cout<<"Constructor Invoked"<<endl;    
        }    
        ~Employee()    
        {    
            cout<<"Destructor Invoked"<<endl;    
        }  
};  
int main(void)   
{  
    Employee e1; //creating an object of Employee   
    Employee e2; //creating an object of Employee  
    return 0;  
}  

Output:

Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
C++ this Pointer
this is a keyword that refers to the current instance of the class. There can be 3 main usage of this
keyword in C++.

o It can be used to pass current object as a parameter to another method.


o It can be used to refer current class instance variable.
o It can be used to declare indexers.

this Pointer Example

#include <iostream>  
using namespace std;  
class Employee {  
   public:  
       int id; //data member (also instance variable)      
       string name; //data member(also instance variable)  
       float salary;  
       Employee(int id, string name, float salary)    
        {    
             this->id = id;    
            this->name = name;    
            this->salary = salary;   
        }    
       void display()    
        {    
            cout<<id<<"  "<<name<<"  "<<salary<<endl;    
        }    
};  
int main(void)
 {  
    Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee   
    Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee  
    e1.display();    
    e2.display();    
    return 0;  
}  
C++ virtual function
o A C++ virtual function is a member function in the base class that you redefine in a derived
class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the function.
o There is a necessity to use the single pointer to refer to all the objects of the different classes.
So, we create the pointer to the base class that refers to all the derived objects. But, when base
class pointer contains the address of the derived class object, always executes the base class
function. This issue can only be resolved by using the 'virtual' function.
o A 'virtual' is a keyword preceding the normal declaration of a function.

Example Program:

#include <iostream>    
{    
 public:    
 virtual void display()    
 {    
  cout << "Base class is invoked"<<endl;    
 }    
};    
class B:public A    
{    
 public:    
 void display()    
 {    
  cout << "Derived Class is invoked"<<endl;    
 }    
};    
int main()    
{    
 A* a;    //pointer of base class    
 B b;     //object of derived class    
 a = &b;    
 a->display();   //Late Binding occurs    
}    

Output:

Derived Class is invoked


Pure Virtual Function

o A virtual function is not used for performing any task. It only serves as a placeholder.
o When the function has no definition, such function is known as "do-nothing" function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual function is a
function declared in the base class that has no definition relative to the base class.

Syntax:

virtual return type function_ name()= 0;   

Data Abstraction in C++

o Data Abstraction is a process of providing only the essential details to the outside world and
hiding the internal detail.
o Representing only the essential details in the program.

Data Abstraction can be achieved in two ways:

o Abstraction using classes


o Abstraction in header files.

Abstraction using classes: An abstraction can be achieved using classes. A class is used to group all
the data members and member functions into a single unit by using the access specifiers. A class has
the responsibility to determine which data member is to be visible outside and which is not.

Abstraction in header files: An another type of abstraction is header file. For example, pow()
function available is used to calculate the power of a number without actually knowing which
algorithm function uses to calculate the power. Thus, we can say that header files hides all the
implementation details from the user.
Unformatted consol input output operations
The following are operations of unformatted consol input / output operations:

A) void get()

It is a method of cin object used to input a single character from keyboard. But its main property is that
it allows wide spaces and newline character.

Syntax:

char c=cin.get();

Example:

#include<iostream>
using namespace std;

int main()
{
char c=cin.get();
cout<<c<<endl;

return 0;
}
B) void put()

It is a method of cout object and it is used to print the specified character on the screen or monitor.

Syntax:

cout.put(variable / character);

Example:

#include<iostream>
using namespace std;

int main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('c'); //Here it prints the character 'c';

return 0;
}
C) getline(char *buffer,int size)

This is a method of cin object and it is used to input a string with multiple spaces.

Syntax:

char x[30];
cin.getline(x,30);

Example:

#include<iostream>
using namespace std;

int main()
{
cout<<"Enter name :";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout<<c<<endl;

return 0;
}

D) write(char * buffer, int n)

It is a method of cout object. This method is used to read n character from buffer variable.

Syntax:

cout.write(x,2);

Example:

#include<iostream>
using namespace std;

int main()
{
cout<<"Enter name : ";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout.write(c,9); //It reads only 9 character from buffer c;

return 0;
}
E) cin

It is the method to take input any variable / character / string.

Syntax:

cin>>variable

F) cout

This method is used to print variable / string / character.

Syntax:

cout<< variable / charcter / string;

Formatted console input output operations


In formatted console input output operations we uses following functions to make output in perfect
alignment. 

A) width(n)

This function is used to set width of the output.

Syntax:

cout<<setw(int n);

B) fill(char)

This function is used to fill specified character at unused space.

Syntax:

cout<<setfill('character')<<variable;

D) precison(n)

This method is used for setting floating point of the output.

Syntax:

cout<<setprecision('int n')<<variable;

E) setflag(arg 1, arg,2)

This function is used for setting format flags for output.


Syntax:

setiosflags(argument 1, argument 2);

F) unsetflag(arg 2)

This function is used to reset set flags for output.

Syntax:

resetiosflags(argument 2);

G) setbase(arg)

This function is used to set basefield of the flag.

Syntax:

setbase(argument);
Managing Output with Manipulators

Manipulators without arguments:

The most important manipulators defined by the IOStream library are provided below.

 endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes
 ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.
 ends: It is also defined in ostream and it inserts a null character into the output stream

 flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output
written on the screen or in the file. Without flush, the output would be the same, but may not
appear in real-time.

Manipulators with Arguments: 

 Some important manipulators in <iomanip> are:

1. setw (val): It is used to set the field width in output operations.


2. setfill (c): It is used to fill the character ‘c’ on output stream.
3. setprecision (val): It sets val as the new value for the precision of floating-point values.
4. setbase(val): It is used to set the numeric base value for numeric values.
5. setiosflags(flag): It is used to set the format flags specified by parameter mask.
6. resetiosflags(m): It is used to reset the format flags specified by parameter mask.

 Some important manipulators in <ios> are:


7. showpos: It forces to show a positive sign on positive numbers.
8. noshowpos: It forces not to write a positive sign on positive numbers.
9. showbase: It indicates the numeric base of numeric values.
10. uppercase: It forces uppercase letters for numeric values.
11. nouppercase: It forces lowercase letters for numeric values.
12. fixed: It uses decimal notation for floating-point values.
13. scientific: It uses scientific floating-point notation.
14. hex: Read and write hexadecimal values for integers and it works same as the setbase(16).
15. dec: Read and write decimal values for integers i.e. setbase(10).
16. oct: Read and write octal values for integers i.e. setbase(10).
17. left: It adjusts output to the left.
18. right: It adjusts output to the right.
Input/output with files
Sr.No Data Type & Description

ofstream
1
This data type represents the output file stream and is used to create files and to write
information to files.

ifstream
2
This data type represents the input file stream and is used to read information from files.

fstream

3 This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files, and
read information from files.

Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And ifstream object
is used to open a file for reading purpose only.

void open(const char *filename, ios::openmode mode);

Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
void close();

Detecting end-of-file

You can detect when the end of the file is reached by using the member function eof()


which has prototype : int eof(); It returns non-zero when the end of file has been reached,
otherwise it returns zero.
Error Handling During File Manipulations
Many users access different files without any predefined access pattern. The following are the
different situations that can arise while manipulating a file;

1. Attempting to open a non-existent file in read mode.

2. Trying to open a read-only marked file in write mode.

3. Trying to open a file with invalid name.

4. Attempting to read beyond the end of file.

5. Sufficient disk space is not available while writing to a file.

6. Attempting to manipulate an unopened file.

7. Stream object created bat not connected to a file.

8. Media (disk) errors reading/writing a file.


C++ Templates
A C++ template is a powerful feature added to C++.

It allows you to define the generic classes and generic functions and thus provides support for
generic programming.

Generic programming is a technique where generic types are used as parameters in algorithms
so that they can work for a variety of data types.

Templates can be represented in two ways:

o Function templates
o Class templates

Function Template

o Generic functions use the concept of a function template. Generic functions define a set of
operations that can be applied to the various types of data.
o The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
o A Generic function is created by using the keyword template. The template defines what
function will do.

Syntax:

template < class Ttype> ret_type func_name(parameter_list)  
{  
    // body of function.  
}  

Example program:

#include <iostream>  
using namespace std;  
template<class T> T add(T &a,T &b)  
{  
    T result = a+b;  
    return result;  
      
}  
int main()  
{  
  int i =2;  
  int j =3;  
  float m = 2.3;  
  float n = 1.2;  
  cout<<"Addition of i and j is :"<<add(i,j);  
  cout<<'\n';  
  cout<<"Addition of m and n is :"<<add(m,n);  
  return 0;  

Function Templates with Multiple Parameters:


We can use more than one generic type in the template function by using the comma to separate the
list

Syntax
 template<class T1, class T2,.....>  
return_type function_name (arguments of type T1, T2....)  
{  
    // body of function.  
}  

Example:
#include <iostream>  
using namespace std;  
template<class X,class Y> void fun(X a,Y b)  
{  
    std::cout << "Value of a is : " <<a<< std::endl;  
    std::cout << "Value of b is : " <<b<< std::endl;  
}  
  
int main()  
{  
   fun(15,12.3);  
   
   return 0;  
}  
Overloading a Function Template
We can overload the generic function means that the overloaded template functions can differ in
the parameter list.

Example Program:

#include <iostream>  
using namespace std;  
template<class X> void fun(X a)  
{  
    std::cout << "Value of a is : " <<a<< std::endl;  
}  
template<class X,class Y> void fun(X b ,Y c)  
{  
    std::cout << "Value of b is : " <<b<< std::endl;  
    std::cout << "Value of c is : " <<c<< std::endl;  
}  
int main()  
{  
   fun(10);  
   fun(20,30.5);  
   return 0;  
}  
CLASS TEMPLATE:

Class Template can also be defined similarly to the Function Template. When a class uses the
concept of Template, then the class is known as generic class.

Syntax:

template<class Ttype>  
class class_name  
{  
  .  
 }  
Example:
#include <iostream>  
using namespace std;  
template<class T>  
class A   
{  
    public:  
    T num1 = 5;  
    T num2 = 6;  
    void add()  
    {  
        std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;  
    }  
    };  
int main()  
{  
    A<int> d;  
    d.add();  
    return 0;  
}  
CLASS TEMPLATE WITH MULTIPLE PARAMETERS
We can use more than one generic data type in a class template, and each generic data type is
separated by the comma.

Syntax
template<class T1, class T2, ......>   
class class_name  
{  
   // Body of the class.  
}  

Example Program:

#include <iostream>  
     using namespace std;  
     template<class T1, class T2>  
    class A   
    {  
         T1 a;  
         T2 b;  
         public:  
        A(T1 x,T2 y)  
       {  
           a = x;  
           b = y;  
        }  
           void display()  
          {  
                 std::cout << "Values of a and b are : " << a<<" ,"<<b<<std::endl;  
           }  
      };  
  
      int main()  
     {  
           A<int,float> d(5,6.5);  
           d.display();  
           return 0;  
     }  
Nontype Template Arguments
The template can contain multiple arguments, and we can also use the non-type arguments In
addition to the type T argument, we can also use other types of arguments such as strings,
function names, constant expression and built-in types.

Syntax:

template<class T, int size>  
class array  
{  
        T arr[size];           // automatic array initialization.  
};  

Example Program:

#include <iostream>  
using namespace std;  
template<class T, int size>  
class A   
{  
    public:  
    T arr[size];  
    void insert()  
    {  
        int i =1;  
        for (int j=0;j<size;j++)  
        {  
            arr[j] = i;  
            i++;  
        }  
    }  
      
    void display()  
    {  
        for(int i=0;i<size;i++)  
        {  
            std::cout << arr[i] << " ";  
        }  
    }  
};  
int main()  
{  
    A<int,10> t1;  
    t1.insert();  
    t1.display();  
    return 0;  
}  
C++ Exception Handling
Exception Handling in C++ is a process to handle runtime errors.

We perform exception handling so the normal flow of the application can be maintained even
after runtime errors.

Exception is an event or object which is thrown at runtime. All exceptions are derived from
std::exception class. It is a runtime error which can be handled. If we don't handle the exception,
it prints exception message and terminates the program.

C++ Exception Classes


In C++ standard exceptions are defined in <exception> class that we can use inside our
programs. The arrangement of parent-child class hierarchy is shown below:
 C++ common exception classes

Exception Description

std::exception It is an exception and parent class of all standard C++ exceptions.

std::logic_failure It is an exception that can be detected by reading a code.

std::runtime_error It is an exception that cannot be detected by reading a code.

std::bad_exception It is used to handle the unexpected exceptions in a c++ program.

std::bad_cast This exception is generally be thrown by dynamic_cast.

std::bad_typeid This exception is generally be thrown by typeid.

std::bad_alloc This exception is generally be thrown by new.


C++ Exception Handling Keywords (or) Exception Handling Mechanisms
We use 3 keywords to perform exception handling:

o try
o catch, and
o throw

try block:

The code which can throw any exception is kept inside(or enclosed in) atry block. Then, when the
code will lead to any error, that error/exception will get caught inside the catch block.

catch block
catch block is intended to catch the error and handle the exception condition. We can have multiple catch
blocks to handle different types of exception and perform different actions when the exceptions occur.

throw statement
It is used to throw exceptions to exception handler i.e. it is used to communicate information about error.

A throw expression accepts one parameter and that parameter is passed to handler.

throw statement is used when we explicitly want an exception to occur, then we can use throw statement to
throw or generate that exception.

Syntax:
try
{
//code
throw parameter;
}
catch(exceptionname ex)
{
//code to handle exception
}
Example Program:
include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int a=10, b=0, c;
// try block activates exception handling
try
{
if(b == 0)
{
// throw custom exception
throw "Division by zero not possible";
c = a/b;
}
}
catch(char* ex) // catches exception
{
cout<<ex;
}
return 0;
}

OUTPUT:
Division by zero not possible
Multiple catch blocks:
We can use more than one catch blocks in a single program
Syntax:
try
{
//code
}
catch(exceptionname ex1)
{
//code to handle exception
}
catch(exceptionname ex2)
{
//code to handle exception
}
Example Program:

#include <iostream>
#include<conio.h>
using namespace std;

int main()
{
int x[3] = {-1,2};
for(int i=0; i<2; i++)
{
int ex = x[i];
try
{
if (ex > 0)
// throwing numeric value as exception
throw ex;
else
// throwing a character as exception
throw 'ex';
}
catch (int ex) // to catch numeric exceptions
{
cout << "Integer exception\n";
}
catch (char ex) // to catch character/string exceptions
{
cout << "Character exception\n";
}}}
OUTPUT:

Integer exception
Character exception
Catch All Exception:

Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.

Syntax:

try

// ...
} catch (...)
{
// ...
}
Example Program:

#include <iostream>
using namespace std;

void func(int a) {
   try {
      if(a==0) throw 23.33;
      if(a==1) throw 's';
   } catch(...) {
      cout << "Caught Exception!\n";
   }
}
int main() {
   func(0);
   func(1);
   return 0;
}

Output
Caught Exception!
Caught Exception!
Rethrowing an Exception

Rethrowing an expression from within an exception handler can be done by calling throw, by itself,
with no exception.

This causes current exception to be passed on to an outer try/catch sequence. An exception can only be
rethrown from within a catch block.

When an exception is rethrown, it is propagated outward to the next catch block.

Example Program:

#include <iostream>
using namespace std;
void MyHandler()
{
   try
   {
       throw “hello”;
   }
   catch (const char*)
   {
   cout <<”Caught exception inside MyHandler\n”;
   throw; //rethrow char* out of function
   }
}
int main()
{
   cout<< “Main start”;
   try
   {
       MyHandler();
   }
   catch(const char*)
   {
      cout <<”Caught exception inside Main\n”;
   }
       cout << “Main end”;
       return 0;
}

Output :

Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end

You might also like