stu nicholls dot com | menu - Professional dropdown #3

click here

Constructors and Destructors

  • C++ provides a special member function called the constructors which enables an object to initialize itself when it is created.
  • This is known as automatic initialization of objects.
  • It also provides another member function called the DESTRUCTOR that destroys the objects when they are no longer required.

  • Constructors

  • A constructor is a special member function whose task is to initialize the objects of its class.
  • It is special because its name is the same as the class name.
  • The constructor is invoked whenever an object of its associated class is created.
  • It is called constructor because it constructs the values of data members of the class.

  • A constructor is declared and defined as follows


    class integer
      {
        int m,n;
     public:
         integer (void);         // constructor declared
         …………
         ……….
        };
    integer :: integer (void)    // constructor defined
       {
         m=0;
         n=0;  
       }
    
  • When a class contains a constructor , it is guaranteed that an object created by the class will be initialized automatically.
  • integer int1;
    not only creates the object int1 but also initializes its data members m and n to zero.
  • A constructor that accepts no parameters is called the default constructor.
  • For eg: default constructor for class A is A :: A()

  • The constructor functions have some special characteristics


    Example

    The constructor function can also be defined within the class


    The parameters of a constructor can be of any type except that of the class to which it belongs.


    Multiple constructors in a class (Overloading of constructors)


    Example here

    Constructors with default arguments


    Destructors


    Example
    click here
    click here
    click here
    Footer1