Thursday 25 April 2013

Constructors and Destructors

Constructor methods are called when an object is created, destructor methods are called
when the object is destroyed. For automatic objects this will be on entry and exit from the
block in which the object is defined. Constructors are frequently used for memory allocation
and initialisation, destructors could be used for deallocation of storage in a data structure.
For a class called string, the constructor is called string and the destructor is called
~string.
Constructors cannot return a value, but it is also invalid to declare them as returning void.
Several constructors can be specified, as long as they have different parameter lists.
Aconstructor that takes no parameters is called the default constructor, and a constructor
that takes an object of the same class as its parameter is called the copy constructor.
The copy constructor takes a reference to an object of the same class. So that const
objects can be used as an initialiser, the parameter should be declared to be const.
class string {
char *str;
public:
string() {} // default constructor
string(const string& s) {}
// copy constructor
~string() {} // destructor
If a constructor can take parameters, then the parameters can be specified using the
following syntax:
string s(parameters);
There are also two methods of calling the copy constructor after having first constructed a
new temporary object:
string s = string(parameters);
or the abbreviated form:
string s = parameter;
For example, the following are all valid ways of initialising a string using a char *
initialiser; the first uses a constructor that takes a char * parameter, the others use the
char * constructor to create a new object, and then use the copy constructor to initialise
the object:
string s1("one");
string s2 = string("two");
string s3 = "three";
The copy constructor is used for passing parameters by value; constructors are also needed
when returning values from functions.
string search(const string s, char c)
{
return string(strchr(s.str,c));
}

When the search function is called, the argument is copied and a new string created
using the copy constructor to initialise it. When the string value is returned from
search, again a new string is created, but this time the constructor used is the one that
takes a char * parameter.

1 comment: