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

Download PDF of This Page (Size: 260K)

Image of Default Constructor

Image of Default Constructor

Image of Default Constructor

5. Memory Allocation for Object

The member function are created and placed in the memory space only once when they are defined in class specification.

All the objects belonging to that class use the same member functions.

Space for member variable is allocated separately for each object because member variable holds different value for different objects.

6. Array of Object

Consider the following program.

  1. class emp
  2. {
  3.     char name [ 30 ] ;
  4.     int empno ;
  5.     public :
  6.     void getdata ( ) ;
  7.     void putdata ( ) ;
  8. };
  9. void main ( )
  10. {
  11.     emp e [ 10 ] ;
  12.     for ( i = 0i < 10i ++)
  13.     e [ i ]. getdata ( ) ;
  14.     for (i = 0i < 10i ++ )
  15.     e [ i ] .putdata ( );
  16. }

In the above program, the ten objects are created, namely, e [ 0 ], e [ 1 ] ---------- e [ 9 ].

The statement e [ i ]. getdata ( ) will get the data of the ith element of the array e.

Constructor

A constructor is a special member function that initializes the objects of its class.

It is special because its name is the same as the class name.

It is invoked automatically whenever an object is created.

It is called constructor because it constructs the values of data members of the class. It does not have any return type, not even void.

A constructor is declared and defined as follows:

  1. class student
  2. {
  3.     int rn;
  4.     int total ;
  5.     public
  6.     student ( )
  7.     {
  8.         rn = 0 ; total = 0 ;
  9.     }
  10. } ;

The declaration

student st ;

Invokes the constructor, student ( ) and assign rn = 0 and total = 0.