Pages

Sunday, 24 August 2014

Constructors and Destructors

Constructors and Destructors
Special member function whose task is to initialize the objects of a class.
A constructor that accepts no parameter is called the default constructor.
A::A (); if no constructor is defined, then the compiler will supply the default constructor.
It can be also defined inline as A () { }; (Once we define a constructor, it is a must? That we define the “do nothing” implicit constructor)
It will be a compilation error if we declare the constructor in the private section. It always must be declared in the public section.
Passing values to parameterized constructors:
  • By calling the constructor Explicitly
Myclass object1 = Myclass (12,12);
  • By calling the constructor Implicitly
Myclass object1 (12,12) ;
Constructors can be inline and can have default values.
The parameters of a constructor cannot be of the class type to which it belongs but can accept a referece to its own class as a parameter.
A::A(A); // illegal
A::A(A&);// Legal (This is Called Copy Constructor)
Simple A = B will not invoke the copy constructor (But it is legal, it will simply assign the values member by member). Only Class_name A (B); or Class_name A=B ; will invoke the copy constructor.
Dynamic Constructors (using new)
Example
Class String {
  Char * str ;
public :
String () {};
String (char *) ;
};

String::String (char *s)
{
      Str= new char [strlen(s)];
     Strcpy (str,s);
}


Constructing Two-dimensional Arrays
class matrix {
  int **p ;  // pointer to the matrix
 int d1,d2;   .. dimensions of the matrix
 matrix (int , int );

} ;
Matrix::matrix (int x,int y)
{
   d1=x;
  d2=y;
 p = new int*[d1] ; // creates an array of pointers of dimensions d1
  for (i=0;i<d1;i++)
   p[i]=new int [d2];
}

const Objects
const matrix X(m,n) ; so the values m and n cannot be changed . And the constant object can call only other  const member fnctions (const keyword appears after the function signature)
Destructors
className::~className(){};
Why required? When an object goes of scope, the destructor is not called implicitly.

No comments:

Post a Comment