Overloaded Constructors
Being functions, constructors can also be overloaded. Typically constructors are
overloaded to provide different ways of creating objects according to the
information available at the time the object is defined.
For example, a class
Person, might contain two
member variables,
name and
number. In this case it might
be useful to have two constructors:
Person(string aName);
Person(string aName, int number);
to cover both the case in which just the name of a person is known and the one
in which name and number are known when an object is created.
Another tyipical case in which more than one constructor is necessary is when
arrays of objects need to be
created dynamically. In such a case, a parameterless constructor must be used
in addition to any other constructor taking one or more parameters.
Example
#include <iostream>
#include <string>
using namespace std;
class Person
{
string name;
int number;
public:
Person() // parameterless constructor, necessary to use
//dynamic allocation
{
number = 0;
}
Person(string aName) // overloaded one-parameter constructor
{
name = aName;
number = 0;
}
Person(string aName, int aNumber) // overloaded constructor
{
name = aName;
number = aNumber;
}
};
int main()
{
Person obj1("Sarah");
Person obj2("Frank", 123456789);
Person *p = new Person[20]; // allocates an array of 20 Person
// objects, no parameters allowed.
delete []p; // de-allocates the array memory
}