Logo 
Search:

C++ Programming Articles

Submit Article
Home » Articles » C++ Programming » BeginnersRSS Feeds

Constructors and Destructor

Posted By: Idelia Miller     Category: C++ Programming     Views: 22922

This is article explains about Constructor, Characteristics of Constructors, Parameterized Constructors, Multiple Constructors in a Class, Constructors With Default Arguments, Dynamic Initialization of Objects, Copy Constructor, Assignments and Initializations, Dynamic Constructors, Constructing Two Dimensional Arrays, Destructors.

Constructors and Destructors

  • Providing initial values with the definition
  • Make the user defined type behave like normal
  • Variable going out of scope to be deleted
  • A special member function constructor which enables an object to initialize when created
  • Destructor is a special member function which destroys the object when no longer required
  • Constructor bears the same name as the object
  • Destructor name is ~ prefixed to constructor 

Constructor

  • It constructs the data values of a class
class integer 
{ int m,n; 
   public : <no data type> integer (void)
        { m = 0 ; n = 0; } };
integer int1;
  • There is no need to write any statement to invoke the constructor function
  • A constructor which accepts no arguments is called a default constructor // integer :: integer()!

Characteristics of Constructors

  • They should be declared in the public section
  • They are automatically invoked and have no return types, neither can they return values
  • They can not be inherited but called by DC Const
  • They can not be virtual nor can we refer to their addresses & they can have default arguments
  • An object with cons or dist can’t member of uni
  • They make implicit calls to new and delete
  • When cons is declared, init becomes mandatory

Parameterized Constructors

  • The constructors that can take arguments
  • integer( int x, int y)  { m = x; n = y; } is a PC
  • now integer int1; will not work
  • integer int1 = integer(8,7) is an explicit call
  • integer int1(8,7) is an implicit call
  • The parameters of a constructor can be any type except the class name to which it belongs
  • It can accept a reference to its own class as a parameter which is known as copy constructor

Multiple Constructors in a Class

integer() {m=0;n=0;}
integer(int x, int y) { m = x; n = y; }
integer(integer & i) { m = i.m; n = i.n }
integer i1;
integer i2;
integer i3(i2);
  • Above is constructor overloading
  • c++ compiler’s implicit constructor creates objects but once we define constructors, we must also define the do-nothing implicit constructor 

Constructors With Default Arguments

  • complex (float real, float imag = 0);
  • complex c(5.0) assigns value 5.0 to real and 0 to imag variable
  • complex c(2.0,3.0) assigns to both of them
  • default constructor and default argument constructor are different
  • A::A() and A::A(int i = 0)
  • When both of the above forms used in the class, they creates ambiguity for the compiler

Dynamic Initialization of Objects

public :
    fixed_deposit() {}
    fixed_deposit(long p, int y, float R = 0.12);
    fixed_deposit(long p, int y, int r);
main() 
{fixed_deposit FD1,FD2,FD3;
// defining and reading p, y, R and r here
FD1 = fixed_deposit(p,y,R); //parameter value 
FD2 = fixed_deposit(p,y);  // provided at run time
FD3 = fixed_deposit(p,y,r);
// displaying them here

Copy Constructor

  • integer i2 = i1 is same as integer i2(i1)
  • The process of initializing through a copy constructor is called copy initialization 
  • A copy constructor takes a reference to an object of the same class as itself
  • i2=i1 will copy member by member but does not call the copy constructor
  • We can not pass by value to a copy constructor
  • Compiler supplies its own CC when not defined

Assignments and Initializations

  • A value of an object is given to another in two distinct situations assignments and initializations
  • Initialization can occur in three ways
    • When one object explicitly initializes another such as declaration
    • When a copy of an object is made to be passed to a function
    • When a temp object is generated (most commonly as a return value
  • CC applies only to initializations

Dynamic Constructors

  • Allocating memory while init objects
class string 
 { char *name; 
     int length;
  public : 
     string() {length = 0; 
                    name=new char[length +1]; }
     string(char *s)
                 {length = strlen(s); 
                   name=new char[length +1];
                   strcpy(name,s);}

void join(string & a, string & b)
   { length = a.length + b.length;
      delete name; name = new char[length+1];
      strcpy(name,a.name); 
      strcat(name,b.name); }
char *first=“This”; //In the main()
string name1(first),name2(“is”),name3(“testing”);
string s1,s2;
s1.join(name1,name2);
s2.join(s1,name3);
s2.display();

Constructing Two Dim Arrays

class matrix
{ int **p; int d1,d2;
  public :
     matrix(int x, int y)
      { d1 =x; d2 =y ; p = new int *[d1];
         for (int i = 0 ; i < d1; ++i)
                    p[i] = new int[d2];  }
     void get_element(int i,int j,int value)
       { p[i][j] = value}
     int & put_element(int i, int j)
       { return p[i][j] }                           
}

Destructors

  • It’s primary purpose is to destroy memory used by an object
  • A default destructor is called when not defined
  • A default constructor allocates space which gets cleaned up by default destructors
  • If we are using dynamic objects, we have to do our own memory cleanup (garbage collection!)
  • It is implicitly called when objects go out of scope
  • It never takes an argument, nor it returns any val
  • Whenever new is used to allocate memory in the constructors, we should use delete to free it
  • A destructor for matrix class 
matrix ::~matrix()
 { for (int i = 0; i< d1; i++) delete p[i];
     delete p; }
  • It gives us control over the end of an object
  • Destruction of dynamic object only is controlled
  
Share: 


Didn't find what you were looking for? Find more on Constructors and Destructor Or get search suggestion and latest updates.

Idelia Miller
Idelia Miller author of Constructors and Destructor is from Frankfurt, Germany.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!