Users Online

· Guests Online: 95

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

C++ Programs on OOP

C++ Programs on OOP

 

 

  • C++ Program to Illustrate Abstract Class
  • C++ Program to Differentiate Between Concrete Class and Abstract Class
  • C++ Program to Illustrate Nested Classes
  • C++ Program to Implement a Class Date
  • C++ Program to Add Two Complex Numbers using Class
  • C++ Program to Illustrate Const Keyword with Member Functions
  • C++ Program to Implement a Class with Mutable Members
  • C++ Program to Demonstrate the use of Static Data Members in a Class
  • C++ Program to Demonstrate Order of Constructor and Destructor Calls
  • C++ Program to Illustrate Copy Constructor in a Class
  • C++ Program to Illustrate the use of Enumerations
  • C++ Program to Demonstrate the use of Keyword Friend
  • C++ Program to Implement atol Function
  • C++ Program to Demonstrate User Defined Exceptions

 

 

 


 

 

 

Abstract Class Program in C++

 

 

 

This C++ program illustrates abstract classes. Abstract classes are used to represent general concepts, which can be used as base classes for concrete classes. An abstract class is one which has atleast one purely virtual function. We can not create instance of such class. The program creates a derived class whose instance is created and is manipulated.

 

Here is the source code of the C++ program which illustrates abstract classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Illustrate Abstract Class
  3.  */
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. class Abstract {
  8.     int i, j;
  9.     public:
  10.         virtual void setData(int i = 0, int j = 0) = 0;
  11.         virtual void printData() = 0;
  12. };
  13.  
  14. class Derived : public Abstract {
  15.     int i, j;
  16.     public:
  17.         Derived(int ii = 0, int jj = 0) : i(ii), j(jj)
  18.         {
  19.             cout << "Creating object " << endl;
  20.         }
  21.         void setData(int ii = 0, int jj = 0)
  22.         {
  23.             i = ii;
  24.             j = jj;
  25.         }
  26.         void printData()
  27.         {
  28.             cout << "Derived::i = " << i << endl
  29.                  << "Derived::j = " << j << endl;
  30.         }
  31. };
  32.  
  33. int main()
  34. {
  35.     // Cannot create an instance of Abstract Class
  36.     // Abstract a;
  37.     Derived d;
  38.  
  39.     cout << "Current data " << endl;
  40.     d.printData();
  41.     d.setData(10, 20);
  42.     cout << "New data " << endl;
  43.     d.printData();
  44. }

 

$ a.out
Creating object 
Current data 
Derived::i = 0
Derived::j = 0
New data 
Derived::i = 10
Derived::j = 20

 

 


 

 

 

Difference between Concrete Class and Abstract Class in C++

 

 

This C++ program differentiates between the concrete and abstract class. An abstract class is meant to be used as a base class where some or all functions are declared purely virtual and hence can not be instantiated. A concrete class is an ordinary class which has no purely virtual functions and hence can be instantiated.

 

Here is the source code of the C++ program which differentiates between the concrete and abstract class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to differentiate between concrete class and abstract class
  3.  */	
  4. #include <iostream>
  5. #include <string>
  6. using namespace std;
  7.  
  8. class Abstract {
  9.     private:
  10.         string info;
  11.     public:
  12.         virtual void printContent() = 0; 
  13. };
  14.  
  15. class Concrete {
  16.     private:
  17.         string info;
  18.     public:
  19.         Concrete(string s) : info(s) { }
  20.         void printContent() {
  21.             cout << "Concrete Object Information\n" << info << endl;
  22.         }
  23. };
  24.  
  25. int main()
  26. {
  27.     /*
  28.      * Abstract a;
  29.      * Error : Abstract Instance Creation Failed
  30.      */
  31.     string s;
  32.  
  33.     s = "Object Creation Date : 23:26 PM 15 Dec 2013";
  34.     Concrete c(s);
  35.     c. printContent();
  36. }

 

$ a.out
Concrete Object Information
Object Creation Date : 23:26 PM 15 Dec 2013


 

Nested Class Program in C++

 

 

 

This C++ program illustrates the use of nested classes. The program uses Node class as a member for Stack class where Node class is nested inside Stack class. The Node class is local to Stack class which can be used outside Stack’s context by using scope operator ‘::’.

 

Here is the source code of the C++ program illustrates the use of nested classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Illustrate Nested Classes
  3.  */
  4. #include <iostream>
  5.  
  6. class Stack {
  7.     class Node {
  8.         public:
  9.             int data;
  10.             Node* next;
  11.             Node(int data, Node* next);
  12.             ~Node();
  13.     }* head;
  14.     public:
  15.         Stack();
  16.         Stack(const Stack& s);
  17.         void operator=(const Stack& s);
  18.         ~Stack();
  19.         void push(int data);
  20.         int peek() const;
  21.         int pop();
  22. };
  23.  
  24. Stack::Node::Node(int data, Node* next)
  25. {
  26.     this->data = data;
  27.     this->next = next;
  28. }
  29.  
  30. Stack::Node::~Node() { }
  31.  
  32. Stack::Stack() { head = NULL; }
  33.  
  34. Stack::Stack(const Stack& s)
  35. {
  36.     head = s.head;
  37. }
  38.  
  39. void Stack::operator=(const Stack& s)
  40. {
  41.     head = s.head;
  42. }
  43.  
  44. void Stack::push(int data)
  45. {
  46.     head = new Node(data, head);
  47. }
  48.  
  49. int Stack::peek() const {
  50.     if(head == 0)
  51.     {
  52.          std::cerr << "Stack empty!" << std::endl;
  53.          return -1;
  54.     }
  55.     else
  56.          return head->data;
  57. }
  58.  
  59. int Stack::pop()
  60. {
  61.     if(head == NULL) return -1;
  62.     int result = head->data;
  63.     Node* oldNode = head;
  64.     head = head->next;
  65.     delete oldNode;
  66.     return result;
  67. }
  68.  
  69. Stack::~Stack()
  70. {
  71.     if(head != NULL)
  72.     {
  73.         while(head->next != NULL)
  74.         {
  75.             Node* temp = head;
  76.             head = head->next;
  77.             delete temp;
  78.         }
  79.     }
  80. }
  81.  
  82. int main()
  83. {
  84.     Stack Integers;
  85.     int value, num;
  86.  
  87.     std::cout << "Enter the number of elements ";
  88.     std::cin >> num;
  89.     while(num > 0)
  90.     {
  91.         std::cin >> value;
  92.         Integers.push(value);
  93.         num--;
  94.     }
  95.     while (( value = Integers.pop() ) != -1)
  96.         std::cout << "Top element of stack  " << value << std::endl; 
  97. }

 

$ a.out
Enter the number of elements 5
1  2  3  4  5
Top element of stack  5
Top element of stack  4
Top element of stack  3
Top element of stack  2
Top element of stack  1



 

Date Class Implementation in C++

 

 

 

This C++ program implements a class – Date. The class uses time header contains a function time() which returns current calender time as an object of type time_t. We can extract various information from this struct by using -> with the pointer to the time structure.

 

Here is the source code of the C++ program implements a class – Date. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to implement Class Date
  3.  */
  4. #include <iostream>
  5. #include <ctime>
  6.  
  7. std::string months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  8.                         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  9. std::string days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri",
  10.                       "Sat"};
  11.  
  12. class Date{
  13.     // Private Members
  14.     private:
  15.         std::string month;
  16.         std::string day;
  17.         int date;
  18.         int year;
  19.     // Public Members
  20.     public:
  21.         // Default Constructor
  22.         Date() { 
  23.                 const int BASE_YEAR = 1900;
  24.                 time_t timer;
  25.                 tm * time;
  26.                 std::time(&timer);
  27.                 time = localtime(&timer);
  28.                 date = time->tm_mday;
  29.                 month = months[time->tm_mon];
  30.                 day = days[time->tm_wday];
  31.                 year = time->tm_year + BASE_YEAR;
  32.         }
  33.         void printDate(void) { 
  34.             std::cout << "Current date " 
  35.                       << this->month << " " << this->day << " "
  36.                       << this->date  << " " << this->year;
  37.         }
  38.         // Destructor
  39.         ~Date() {}
  40. };
  41.  
  42. int main()
  43. {
  44.     Date d;
  45.  
  46.     d.printDate();
  47. }

 

$ a.out
Current date Oct Mon 7 2013



 

 

C++ Program to Add Two Complex Numbers using Class

 

 

 

 

This is a C++ Program to add two Complex Numbers.

Problem Description

We have to input the real and imaginary parts of two complex numbers separately and add them using classes and objects in C++.

Expected Input and Output

1. When the real and imaginary part both are positive.

First Complex Number = 5 + 6i
Second Complex Number = 1 + 3i

Output= 6 + 9i

2. When any one of the imaginary or real part is negative.

First Complex Number = -4 + 6i
Second Complex Number = 5 + (-3i)

Output= 1 + 3i

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement

3. When both real and imaginary parts are negative.

First Complex Number = -5 + -(6i)
Second Complex Number = -3 + -(5i)

Output= -8 + -11i

Problem Solution

In this problem, we are going to create a function that adds two complex numbers. First the user has to provide real and imaginary parts as input for both the complex numbers. After that the real part of first complex number will be added with the real part of second one, similarly the imaginary part of first complex number will be added with the imaginary part of second complex number.

Program/Source Code

Here is source code of the C++ Program to add two Complex Numbers using Classes and Objects. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on Windows 10. The program output is also shown below.

  1. /* C++ Program to add two Complex Numbers */
  2. #include<iostream>
  3. using namespace std;
  4. class Complex{
  5. public:
  6.     int real;
  7.     int imag;
  8.      /* Function to set the values of
  9.       * real and imaginary part of each complex number
  10.       */
  11.      void setvalue()
  12.     {
  13.         cin>>real;
  14.         cin>>imag;
  15.     }
  16. 	/* Function to display the sum of two complex numbers */
  17.     void display()
  18.     {
  19.         cout<<real<<"+"<<imag<<"i"<<endl;
  20.     }
  21. 	/* Function to add two complex numbers */
  22.  
  23.     void sum(Complex c1, Complex c2)
  24.     {
  25.         real=c1.real+c2.real;
  26.         imag=c1.imag+c2.imag;
  27.     }
  28.     };
  29. int main()
  30.     {
  31.         Complex c1,c2,c3;
  32.         cout<<"Enter real and imaginary part of first complex number"<<endl;
  33.         c1.setvalue();
  34.         cout<<"Enter real and imaginary part of second complex number"<<endl;
  35.         c2.setvalue();
  36.         cout<<"Sum of two complex numbers is"<<endl;
  37.         c3.sum(c1,c2);
  38.         c3.display();
  39.     return 0;
  40.     }
Program Explanation

Here in this program we have created a few functions.

1. setvalue()
This function allows us to take input for real and imaginary parts of both the complex numbers. To take in real and imaginary part as an input for first complex number we have called this function using an object c1. So, this function sets the real and imag values for first complex number. Similarly to set the values of real and imaginary part of second complex number, we can call it using a new object c2.

2. sum()
This function takes in two complex numbers as a parameter. Using this function we have added the real parts of both the complex numbers together and stored them into variable real which is the real part of the resultant complex number. Similarly we have added the imaginary parts of both the complex numbers and stored the result into variable imag which is the imaginary part of the resultant complex number.

3. display()
We have called this function using an object for the resultant complex number, to display the real and imaginary parts of the resultant complex number obtained after addition.

Runtime Test Cases
1. Enter real and imaginary part of first complex number
   5
   6
   Enter real and imaginary part of second complex number
   1
   3
   Sum of two complex numbers is
   6+9i
 
2. Enter real and imaginary part of first complex number
   -4
   6
   Enter real and imaginary part of second complex number
   5
   -3
   Sum of two complex numbers is
   1+3i
 
3. Enter real and imaginary part of first complex number
   -5
   -6
   Enter real and imaginary part of second complex number
   -3
   -5
   Sum of two complex numbers is
   -8+-11i


 

 


 

 

 

C++ Program to Illustrate Const Keyword with Member Functions

 

 

 

This C++ program illustrates the const keyword with member functions. The functions with a const keyword specified before the function definition prevents the calling of non-const data members for a given instance of the class. It also prevents t

 

Here is the source code of the C++ program which illustrates the const keyword with member functions. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to illustrate physical constness
  3.  */
  4. #include <iostream>
  5. #include <string>
  6. #include <sstream>
  7. using namespace std;
  8.  
  9. class A {
  10.     private:
  11.         int i, j;
  12.     public:    
  13.         A(int ii = 0, int jj = 0) : i(ii), j(jj) {}
  14.         void changeData(int ii, int jj ) {
  15.             i = ii;
  16.             j = jj; 
  17.         }
  18.         string getResponse() const {
  19.             string s;
  20.             stringstream ss;
  21.             ss << "i = " << i << ", j = " << j << "\n";
  22.             s = ss.str();
  23.             return s;
  24.         }
  25.         void makeSomeChanges() const;
  26.  
  27. };
  28.  
  29. /*
  30.  * Can't change A::i or A::j
  31. void A::makeSomeChanges() const {
  32.     i = i + 10;
  33.     j = j + 10;
  34. }
  35. */
  36.  
  37. int main()
  38. {
  39.     A a(10, 20);
  40.  
  41.     cout << "A a(10, 20)           : " << a.getResponse();
  42.     a.changeData(30, 40);
  43.     cout << "A::changeData(30, 40) : " << a.getResponse();
  44.     // a.makeSomeChanges();
  45.     cout << "A::makeSomeChanges()  : " << a.getResponse();
  46. }

 

$ a.out
A a(10, 20)           : i = 10, j = 20
A::changeData(30, 40) : i = 30, j = 40
A::makeSomeChanges()  : i = 30, j = 40


 

 

C++ Program to Implement a Class with Mutable Members

 

 

This C++ program illustrates the concept of mutable keyword in classes. The keyword mutable enables a const member function to change a variable. This explains the concept of logical const-ness of the object where the object changes in a way that it is not apparent through a public interface.

 

Here is the source code of the C++ program illustrates the concept of mutable keyword in classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Implement a Class with Mutable Members
  3.  */
  4. #include <iostream>
  5.  
  6. class A {
  7.     private:
  8.         int i;
  9.         mutable int j;
  10.     public:
  11.         A(int ii = 0, int jj = 1) : i(ii), j(jj) { }
  12.         void change() const;
  13.         void print();
  14. };
  15.  
  16. void A::change() const
  17. {
  18.     // Mutable variable 
  19.     j++;
  20. }
  21.  
  22. void A::print()
  23. {
  24.     std::cout << "A::i = " << i << std::endl
  25.               << "A::j = " << j << std::endl;
  26. }
  27.  
  28. int main()
  29. {
  30.     A a;
  31.  
  32.     std::cout << "Before A::change()" << std::endl;
  33.     a.print();
  34.     a.change();
  35.     std::cout << "After  A::change()" << std::endl;
  36.     a.print();
  37. }

 

$ a.out
Before A::change()
A::i = 0
A::j = 1
After  A::change()
A::i = 0
A::j = 2



 

C++ Program to Demonstrate the use of Static Data Members in a Class

 

 

This C++ program demonstrates the use of static members in a class. A static data member is shared by all objects of a class. We can put a static data member inside a class but we would have to initialize it outside the class using scope resolution operator (::).

 

Here is the source code of the C++ program demonstrates the use of static members in a class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Demonstrate a Class with Static Members
  3.  */
  4. #include <iostream>
  5.  
  6. class Car {
  7.     private:
  8.         static std::string colour;
  9.         std::string brand;
  10.         std::string state;
  11.         int model;  
  12.     public:
  13.         Car(int model, std::string brand, std::string state = "off") 
  14.         { 
  15.             this->model = model; 
  16.             this->brand = brand;
  17.             this->state = state;
  18.         }
  19.         void engineOn()
  20.         {
  21.             state = "on";   
  22.         }
  23.         void knowState()
  24.         {
  25.             std::cout << "Is " << brand << " ready?" << std::endl;
  26.         }
  27.         void isReady()
  28.         {
  29.             if(state == "on")
  30.                 std::cout << colour << " " << brand
  31.                           << " is ready to go!" << std::endl;
  32.             else
  33.                 std::cout << colour << " " << brand
  34.                           << " is not ready!" << std::endl;
  35.         }
  36. };
  37.  
  38. // Definition of a protected static member
  39. // Legal expression
  40. std::string Car::colour = "Red";
  41.  
  42. int main()
  43. {
  44.     Car chevy(1965, "Chevy Mint", "on");
  45.     chevy.knowState();
  46.     chevy.isReady();
  47.     Car ferrari(1965, "Ferrari" );
  48.     ferrari.knowState();
  49.     ferrari.isReady();
  50. }

 

$ a.out
Is Chevy Mint ready?
Red Chevy Mint is ready to go!
Is Ferrari ready?
Red Ferrari is not ready!



 

 

Order of Constructor and Destructor Calls in C++

 

 

This C++ program demonstrates the order of constructor and destructor calls for globally and locally initialized objects. The constructors of global objects are initialized earlier than local objects and the destructors for local objects are called earlier than global objects. Thus we can say that scope of a global object is larger than a local objects.

 

Here is the source code of the C++ program demonstrates the order of constructor and destructor calls for globally and locally initialized objects. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate order of constructor and destructor calls
  3.  */
  4. #include <iostream>
  5.  
  6. class A {
  7.     int i;
  8.     public:
  9.         A(int ii = 0) : i(ii)
  10.         {
  11.             std::cout << "A::A" << i << "() constructor "
  12.                       << std::endl;
  13.         }
  14.         ~A()
  15.         {
  16.             std::cout << "A::~A" << i << "() destructor "
  17.                       << std::endl;
  18.         }
  19. };
  20.  
  21. A a1(1);
  22.  
  23. int main()
  24. {
  25.     A a2(2);
  26. }

 

$ a.out
A::A1() constructor
A::A2() constructor
A::~A2() destructor
A::~A1() destructor




Copy Constructor Program in C++

This C++ program illustrates copy-constructor in a class. A copy constructor is a special constructor for a class that is used to make a copy of an existing instance of the class. A copy-constructor looks like a constructor with an object of same class as an argument.

Here is the source code of the C++ program which illustrates copy-constructor in a class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

1. /*

2.  * C++ Program to illustrate copy-constructor in a class

3.  */

4. #include <iostream>

5. using namespace std;

6.  

7. class Base {

  1. 8.     int i;
  2. 9.     public:
  3. Base(int ii = 0): i(ii) { }
  4. Base(const Base& b)
  5. {
  6.         this->i = b.i;
  7. }
  8. void setData(int ii) { i = ii; }
  9. int getData() { return i; }

17.};

18. 

19.int main()

20.{

  1. Base b;

22. 

  1. cout << "b::getData = " << b.getData() << endl;
  2. cout << "b::setData = 10" << endl;
  3. b.setData(10);
  4. cout << "b::getData = " << b.getData() << endl;
  5. cout << "Calling copy-constructor on c" << endl;
  6. Base c(b);
  7. cout << "c::getData = " << c.getData() << endl;

30.}

$ a.out

b::getData = 0

b::setData = 10

b::getData = 10

Calling copy-constructor on c

c::getData = 10

 

 

 


Enumerations Program in C++

This C++ Program which illustrates the use of enumerations. The program creates an enumeration of months, creates an enumeration variable, assigns it a month value and prints a comment on the current month.

 

Here is source code of the C++ program which illustrates the use of enumerations. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Illustrate the use of Enumerations
  3.  */

  4. #include<iostream>
  5. using namespace std;

  6. enum Month {January = 1 ,February = 2, March = 3, April = 4, May = 5,
  7.            June = 6, July = 7, August = 8, September = 9, October = 10,
  8.             November = 11, December = 12};

  9. int main()
  10. {
  11.     Month month;
  12.     month = August;

  13.     cout << "The month is August." << endl;
  14.     /* Printing comments on current Month */
  15.     if (month >= March && month <= May)
  16.         cout << "Yay, It is Spring!" << endl;
  17.     else if (month >= June && month <= August)
  18.         cout << "It is Summer, Who needs an Ice Cream?" << endl;
  19.     else if (month >= September && month <= November)
  20.         cout << "I am enjoying Autumn, Aren't You?" << endl;
  21.     else
  22.         cout << "Ooh, It is very cold outside! It's Winter!" << endl;
  23. }
$ g++ main.cpp
$ ./a.out
The month is August.
It is Summer, Who needs an Ice Cream?


Friend Function Program in C++

 

This C++ program demonstrates the use of keyword friend in classes. The program creates two classes ‘X’ and ‘Y’ and declares one class as ‘friend’ in another. By declaring friend, we mean that the friend class ‘Y’ will gain access to all the data members of the class ‘X’. The member functions of the friend class ‘Y’ can now change the values of data member of objects of class ‘X’ when passed as parameters.

Here is the source code of the C++ program demonstrates the use of keyword friend in classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

 

/*

 * C++ Program to Demonstrate the use of Keyword Friend

 */

 #include <iostream>

 

class X {

    private:

        int j;

    protected:

        int k;

    public:

        X(int jj = 1, int kk = 2) : j(jj), k(kk) {}

        friend class Y;

        friend void fun();

};

 

class Y {

    int l;

    public:

        Y(int ll = 0) : l(ll) {}

        void change(const X& x);

        void printValue()

        {

            std::cout << "Y::l = " << l << std::endl;

        }

};

 

void Y::change(const X& x)

{

    l = x.j;

    std::cout << "Y::change() : Y::l is now X::j " << std::endl;

}

 

void fun()

{

    X x;

    std::cout << "fun::X::j  = " << x.j << std::endl;

}

 

int main()

{

    X x;

    Y y;

 

    y.printValue();

    fun();

    y.change(x);

    y.printValue();

}

$ a.out

Y::l = 0

fun::X::j  = 1

Y::change() : Y::l is now X::j

Y::l = 1



C++ Program to Implement atol Function

This C++ Program which implements atol function which converts a C++ string to an integer value. The function atol( ) skips any trailing blanks and alphabets and if the string iterator has reached the end of the string, a negative value is returned to indicate that no digit is present in the string else the iterator goes through the remaining string until a non-digit character is encountered.

Here is source code of the C++ program which implements atol function which converts a C++ string to an integer value. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Implement atol Function
  3.  */
  4. #include <iostream>
  5. #include <cctype>
  6. #include <string>

  7. /* Function converts string to integer */
  8. int atol(std::string s)
  9. {
  10.     int num = 0;
  11.     std::string::const_iterator i;
  12.     for (i = s.begin(); i != s.end(); i++)
  13.     {
  14.         if (*i == ' ' || *i == '\t' || isalpha(*i))
  15.            continue;
  16.         else
  17.             break;
  18.     }
  19.     if (i == s.end())
  20.         return -1;
  21.     for (std::string::const_iterator j = i; j != s.end(); j++)
  22.     {
  23.         if (isdigit(*j))
  24.             num = num * 10 + (*j - '0');
  25.         else
  26.             break;
  27.     }
  28.     return num;
  29. }

  30. int main()
  31. {
  32.     std::string s;
  33.     int num; 
  34.     std::cout << "Enter a numerical string : ";
  35.     std::cin >> s;
  36.     num = atol(s);
  37.     if (atol(s) >= 0)
  38.        std::cout << "The Numerical Value is  : " << num << std::endl;
  39.     else
  40.         std::cout << "No numerical digit found " << std::endl;
  41. }
$ g++ main.cpp
$ ./a.out
Enter a numerical string :      956
The Numerical Value is  : 956
$ ./a.out
Enter a numerical string : nonumber
No numerical digit found

User Defined Exceptions in C++

This C++ program demonstrates user-defined exceptions. The program derives an exception class from the standard exception class named Divide_By_Zero_Exception. The try block throws the Divide_By_Zero_Exception object and catch block handles it by executing the what() member function.

Here is the source code of the C++ program which demonstrates user-defined exceptions. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate user-defined exceptions
  3.  */
  4. #include <iostream>
  5. #include <exception>
  6. using namespace std;

  7. class Divide_By_Zero_Exception : public exception{
  8.    public:
  9.         const char * what() const throw()
  10.         {
  11.             return "Divide By Zero Exception\n";
  12.         }
  13. };

  14. int main()
  15. {
  16.     try
  17.     {
  18.         int a, b;
  19.         cout << "Enter two numbers : ";
  20.         cin >> a >> b;
  21.         // compute a / b
  22.         if (b == 0)
  23.         {
  24.             Divide_By_Zero_Exception d;
  25.             throw d;
  26.         }
  27.         else
  28.         {
  29.             cout << "a / b = " << a/b << endl;
  30.         }
  31.     }
  32.     catch(exception& e)
  33.     {
  34.         cout << e.what();
  35.     }
  36. }
$ a.out
Enter two numbers : 10 2
a / b = 5
$ a.out
Enter two numbers : 1 0
Divide By Zero Exception

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.72 seconds
10,832,212 unique visits