I'm not certain I understand your question but I will do my best to clear up any misconceptions you may have. An object is
always created with a constructor. What I think you are asking for is a constructor that isn't a
default constructor.
Take the following class for instance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class pair
{
public:
pair();
pair(short first_number, short second_number);
private:
short first;
short second;
}
int main()
{
//code goes here
}
pair::pair(): first(0), second(0)
{
//default constructor
//sets first and second equal to zero
}
pair::pair(short first, short second): first(first_number), second(second_number)
{
//constructor with two arguments
//sets first equal to first_number and second equal to second_number
}
|
The code above would let you create an object using a default constructor and a non-default constructor. To define an object using the default constructor you would create the object as follows:
pair default_pair;
The above code would set default pair to have default_pair.first equal to zero and default_pair.second equal to zero.
To create an object with an arbitrary set of numbers you would do the following:
pair second_pair(1, 2);
The above code would set second_pair.first equal to 1 and second_pair.second equal to 2. When the computer creates default_pair it sees no arguments and so it uses the constructor with no arguments. Likewise, when the computer creates the object second_pair it sees two arguments and so it uses the constructor with two arguments.
Alternatively you could have created the constructors as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class pair
{
public:
pair(short first_number = 0, short second_number = 0);
private:
short first;
short second;
}
int main()
{
//code goes here
}
pair::pair(short first, short second): first(first_number), second(second_number)
{
//constructor with two arguments
//sets first equal to first_number and second equal to second_number
}
|
The above code does the same thing as the earlier code. If you create an object with no arguments then zero is plugged in for the members first and second. If you do use two arguments then you can set first and second to the value of your arguments. With this method you can also use one argument for creating pair type objects but I wouldn't recommend doing this.