NIOS Computer: Chapter 13 – Classes & Objects with Constructors/Destructors Part 5

Doorsteptutor material for UGC is prepared by world's top subject experts: Get full length tests using official NTA interface: all topics with exact weightage, real exam experience, detailed analytics, comparison and rankings, & questions with full solutions.

Download PDF of This Page (Size: 220K)

Image of Default Constructor

Image of Default Constructor

Image of Default Constructor

Image of constructor

Image of Constructor

Image of constructor

(I) Default Constructor

A constructor that accepts no parameter is called default constructor.

If no such constructor is defined, then the compiler supplies a default constructor.

In that case, it is called nothing-to-do constructor.

(II) Parameterize Constructors

The constructors that can take arguments are called parameterized constructors.

  1. class student
  2. {
  3.     int rntotal ;
  4.     public
  5.     student (int xint y)
  6.     {
  7.         rn = x ; total = y ;
  8.     }
  9. } ;

When the object is created, we must supply arguments to the constructor function. This can be done in two ways:

  • By calling the function explicitly

  • By calling the function implicitly

The first call is implemented as follows:

student S1 = student ( 1, 70 ) ;

The second call is implemented as follows:

student S1 ( 1, 70 ) ;

The second method is used very often as it is shorter.

(III) Copy Constructor

A copy constructor takes a reference to an object of the same class as itself as an argument. Consider the following program segment:

  1. class student
  2. {
  3.     int rntotal ;
  4.     public :
  5.     student (int xint y )
  6.     {
  7.         rn = x ; total = y ;
  8.     }
  9.     student (Student & i )
  10.     {
  11.         rn = irn ;
  12.         total = itotal ;
  13.     }
  14. };

The above program has both parameterized and copy constructor. The statement

student S1 ( 1, 75 ) ;

Calls the parameterized constructor and assigns 1 to rn and 75 to total. The statement

student S2 (S1) ;

uses copy constructor and initializes an object S2 from another object S1. Another form of the statement is

student S2 = S1 ;

The process of initialization through a copy constructor is known as copy initialization.

Note that the statement

S2 = S1 ;

does not invoke the copy constructor. However, it simply assigns the value of S1 to S2, member by member.

Developed by: