Showing posts with label Constructor. Show all posts
Showing posts with label Constructor. Show all posts

Is it possible to throw an exception through a constructor?

Yes, we can! We cannot return any error value from the constructor, as the constructor doesn’t have any return type. In such situation, by throwing an exception we can pass value to catch block. 

This is shown in the following example:
#include <iostream.h>
class sample
{
     public:
           sample ( int i )
           {
                 if ( i == 0 ) throw "error"; 
           } 
};
void main( )
{
     try
     {
          sample s ( 0 );
     }
     catch ( char * str ) 
     {
          cout << str; 
     }

Constructors and Destructors

Constructor:
Constructors in C++ are special member functions of a class. A Constructor is a function that initilizes the members of object.There can be any number of overloaded constructors inside a class.The Constructor is automatically called whenever an object is created or dynamically allocated using "new" operator.

If no constructor is supplied then a default one is created by the compiler without any parameters.If you supply a constructor with parameters then default will NOT be created.

Some Points about Constructor:
  • Constructors have the same name as the class.
  • Constructors do not return any values.
  • Constructors are invoked first when a class is initialized. Any initialization for the class members,memory allocations are done at the constructor.
  • Constructors are never virtual.
Ex:
       Class Sample
       {
              public:
                      Sample()
                      { 
                           ..
                      }
       };

Destructor:
Destructor s in C++ also have the same name,except that they are preceded by a '~' operator. The destructors are called when the object of a class goes out of scope.The main use of destructors is to release dynamic allocated memory.Destructors are used to free memory,release resources and to perform other cleanup.If the destructor is not declared inside a class,the compiler automatically create a default one.

If the constructor/destructor is declared as private,then the class cannot be instantiated.

Ex:
        ~Sample()

Why there are no virtual constructors but there are virtual destructors?

To call a virtual constructor, the V-table should be already in memory. However, there is no pointer to v-table in memory because the object has not been created. The object will be created when you have the constructor in place.