انت هنا الان : شبكة جامعة بابل > موقع الكلية > نظام التعليم الالكتروني > مشاهدة المحاضرة

Constructors and Destructors

الكلية كلية العلوم للبنات     القسم قسم الحاسبات     المرحلة 2
أستاذ المادة مهدي عبد سلمان المسلماوي       3/29/2011 10:21:01 AM

constructors and destructors

 

we have used member functions such as putdata( ) and setvalue( ) to provide initial values to the private member variables. for example, the following statement

                                              a.input()

 

invokes the member function input(), which assign the initial values to the data items of object a.

similarly, the statement

                                              x.getdata(100,299.95)

 

passes the initial values as argument to the function getdata( ), where these values are assigned to the private variables of object x. all these  "function call" statements are used with the appropriate objects that have already been created. we cannot use these functions to initialize the member variables at the time of creation of their objects.

since, one of  the aims of c++ is to create user defined data types such as class, that behave very similar to the built-in types. this means that we should be able to initialize a class type variable (object) when it is declared, much the same way as initialization of an ordinary variable. for example,

                      int m = 20

 

                      float x = 5.75

 

are valid initialization statements for basic data types.

similarly, when a variable of built-in type goes out of scope, the compiler automatically destroys the variable. however, it has not happened with the objects we have so far studied.

some features of classes need to be explored that would enable us to initialize the objects when they are created and destroy  them when their presence is no longer necessary.

                      c++ provides a special member function called the constructor, 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: 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 construct 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 like the one defined above, it is guaranteed that an object created by the class will be initialized automatically. for example, the declaration

                                              integer int1 //object int1 created

 

not only creates the object int1 of type integer but also initializes its data members m and n to zero. there is no need to write any statement to invoke the constructor function( as we do with the normal member function).

a constructor that accepts no parameters is called the default constructor. the default constructor for class a is a::a( ). if no such constructor is defined, then the compiler supplies a

                                              a a

 

invokes the default constructor of the compiler to create the object a.

the constructor functions have some special characteristics:

  • they should be declared in the public section.
  • they are invoked automatically when the objects are created.
  • they do not have return types, not even void and therefore, they cannot return values.
  • they cannot be inherited, though a derived class can call the base class constructor.
  • like other c++ functions, they can have default arguments.
  • constructors cannot be virtual.
  • we cannot refer to their address.
  • an object with a constructor (or destructor) cannot be used as a member of union.
  • they make implicit calls to the operators new and deleting when memory allocation is required.

remember, when a constructor is declared for a class, initialization of the class objects becomes mandatory.

parameterized constructors

 

the constructor integer( ), defined above, initializes the data members of all the objects to zero. however, in practice it may be necessary to initialize the various data elements of different objects with different values when they are created. c++ permits us to achieve this objective by passing arguments to the constructor function when the objects are created. the constructors that can take arguments are called parameterized constructors.

 

the constructor integer( ) may be defined to take argument as shown below:

                      class integer

 

                      {

 

                                              int m,n

 

                            public:

 

                                              integer( int x, int y) // parameterized constructor

 

                                              ……..

 

                                              ……..

 

                      }

 

                      integer::integer(int x, int y)

 

                      {    m=x n=y }

 

when a constructor has been parameterized, the object declaration statement such as

                                              intger int1

 

may not work, we must pass the initial values as argument to the constructor function when an object is declared, this can be done either by calling the constructor explicitly like :

integer int1=integer(0,100) // explicit call

 

  or implicitly such as:

                                              integer int1(0,100)   // implicit call

 

this method, sometimes called the shorthand method, is used very often as it is shorter, looks better and easy to implement.

remember, when the constructor is parameterized, we must provide appropriate arguments for the constructor. example:

//////////////////////////// class with constructors ] /////////////////////

 

// include section -

 

#include < iostream.h>

 

// class declaration -

 

class integer

 

{

 

                  int m,n

 

      public:

 

                  integer(int, int)       // constructor declaration

 

                  void display(void)

 

                  {

 

                                          cout < < " m = "< < m < < "\n"

 

                                          cout < < " n = " < < n < < "\n"

 

                    }

 

}

 

// - member function declaration -

 

integer :: integer ( int x , int y)  // constructor defined

 

{

 

                      m=x n=y

 

}

 

int main(void)

 

{

 

                    integer int1(0,100)                               // implicit call

 

                    integer int2=integer(25, 75) // explicit call

 

                    cout < < "\n object1" < < "\n"

 

                    int1.display( )

 

                    cout < < "\n object2" < < "\n"

 

                    int2.display( )

 

}

 

/////////////////////////////// [ program 6.1 ] ///////////////////////////////

 

the output will be :

                      object1

                      m = 0

                      n = 100

                      object2

                      m=25

                      n=75

the constructor function can also be defined as inline function.

class integer

 

{

 

                      int m.n

 

          public:

 

                      integer( int x, int y)

 

                      {

 

                                              m=x y=n

 

                      }

 

                      ………

 

                      ………

 

}

 

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

                                              class a

 

                                              {

 

                                                                      …….

 

                                                                      …….

 

                                                  public:

 

                                                                      a(a)

 

                                              }

 

is illegal.

however, a constructor can accept a reference to its own class as a parameter. thus is,

                                              class a

 

                                              {

 

                                                                      ……

 

                                                                      ……

 

                                                      public:

 

                                                                      a(a& )

 

                                              }

 

is valid. in such cases, the constructor is called the copy constructor.

 

multiple constructors in a class

 

so far, we have used two kinds of constructors. they are:

                                              integer( )               // no arguments

 

                                              integer( int, nt ) // two arguments

 

in the first case, the constructor itself  supplies the data values and no values are passed by the calling program. in the second case, the function call passes the appropriate values from main ( ).

c++ permits us to use both these constructors in the same class. for example, we could define a class as follows:

                                              class integer

                                              {

 

                                                                      int m,n

 

                                                      public:

 

                                                                      integer ( ){m=0 n=0 }                    // constructor 1

 

                                                                      integer ( int a, int b)

 

                                                                      { m=a n=b }                                                  // constructor 2

 

                                                                      integer(integer & i)

 

                                                                      {m=i.m n=i.n }

 

                                              }

 

this decelerates three constructors for an integer objects. so,

                                              integer i1

 

would automatically invoked the first constructor and set both m and n of  i1 to zero. the stament

                                              integer i2(20,40)

 

would call the second constructor which will initialize the data members m and n of i2 to 20 and 40 respectively. finally, the statement

                                              integer i3(i2)

 

would invoked the third constructor which copies the values of i2 into i3. that is, it sets the values of every data element of i3 to the corresponding data element of i2. this process is called constructor overloaded.

example:

/////////////////////////[  overloded constructors]///////////////////////

 

class complex

 

{

 

                  float x,y

 

          public:

 

                  complex(void){ }

 

                  complex(float a) { x=y=a }

 

                  complex(float real, float imag}

 

                  { x=real y=imag }

 

                    friend complex sum( complex, complex)

 

                    friend void show(complex)

 

}

 

complex sum (complex c1, complex c2)

 

{

 

                  complex c3

 

                  c3.x=c1.x+c2.x

 

                  c3.y=c1.y+c2.x

 

                  return(c3)

 

}

 

void show (complex c)

 

{

 

        cout< < c.x< < "+j" < < c.y< < "\n"

 

}

 

int main(void)

 

{

 

                complex a(2.7, 3.5)         // define & initialize

 

                complex b(1.6)                        // define & initialize

 

                complex c                                     // define

 

                c=sum(a,b)

 

                  cout < < "a = " show(a)

 

                  cout < < "b = " show(b)

 

                  cout < < "c = " show (c)

 

// another way to give initial values (  second method)

 

                complex p,q,r

 

                p=complex(2.5, 3.9)

 

                q=complex( 1.6,2.5)

 

                r=sum(p,q)

 

                cout < < "p= " show(p)

 

                cout < < "q= " show(q)

 

                cout < < "r= " show (r)

 

return 0

 

}

 

///////////////////////////////< program 6.2 > //////////////////////////////////

 

the output would be:

                      a= 2.7 +j3.5

                      b= 1.5 +j1.6

                      c= 4.3 +5.1

 

                      p= 2.5 +j3.9

                      q=1.6 +j2.5

                      r= 4.1 +j6.4

copy constructor: it is used to declare and initialize an object from another object. for example, the statement:

                                              integer i2(i1)

 

would define the object i2 and at same time initialize it to the values of i1. another form of this is

                                              integer i2=i1

the process of initializing through a copy constructor is known as copy initialization. remember, the statement

                                              i2=i1

would not invoke the copy constructor, it my be done by overloading the operator "=".

 


destructors

 

it is used to destroy the objects that have been created by a constructor. the destructor is a member function whose name is the same as the class name but it is preceded by tilde, for the class integer can be defined as shown below:

                                              ~integer( ) { }

a destructor never takes any argument nor does it return any value. it will be invoked implicitly by the compiler upon exit from the program ( or block or function as the case may be) to clean up storage that is no longer accessible. it is a good practice to declare destructors in a program since it release memory space for future use.

example :

///////////////////////[ implementation of the destructors]///////////////////////////

 

// - include section -

 

# include < iostream.h>

 

//

 

int count=0

 

// - class declaration

 

class alpha

 

{

 

              public:

 

                        alpha(void)

 

                          {

 

                                            count++

 

                                            cout < < "\nno. of object created "< < count

 

                            }

 

                            ~alpha(void)

 

                                {

 

                                                cout < < "\nno. of object destroyed"< < count

 

                                                count

 

                                    }

 

  }

 

 

  // main section -

 

int main(void)

 

{

 

                cout < < "\n\nenter main \n"

 

                  alpha a1,a2,a3

 

                  {

 

                                                    cout < < "\n\nenter block 1\n"

 

                                                      alpha a5

 

                    }

 

                      //

 

                        {

 

                                                            cout < < "\n\nenter block 2\n"

 

                                                            alpha a6

 

                          }

 

                          cout < < "\n\nr-enter main\n"

 

return 0

 

}

 

/////////////////////////////< program 6.7> ////////////////////////////////////

 

 

 


المادة المعروضة اعلاه هي مدخل الى المحاضرة المرفوعة بواسطة استاذ(ة) المادة . وقد تبدو لك غير متكاملة . حيث يضع استاذ المادة في بعض الاحيان فقط الجزء الاول من المحاضرة من اجل الاطلاع على ما ستقوم بتحميله لاحقا . في نظام التعليم الالكتروني نوفر هذه الخدمة لكي نبقيك على اطلاع حول محتوى الملف الذي ستقوم بتحميله .