[cs13001] More than one constructor?
Mikhail Nesterenko
mikhail at cs.kent.edu
Sat Nov 17 19:36:19 EST 2012
>
> I was reading about constructors, and I was wondering, I read that you can have multiple constructors in a class, something like:
>
> class Date {
> public:
> Date ( int, int, int);
> Date (int, int);
> Date (); // void constructor
>
> My question is, how does the compiler know which constructor are we
> using? By the numbers of arguments we pass?
>
It is perfectly legal to have multiple constructors. This technique is
called function (in this case constructor) overloading. Since
constructor have the same name as a class, they are differentiated by
the number and type of the parameters.
> What if we had 2 constructors that are Date (int, int, int); would
> that work? If yes, how would the compiler know which one we're
> using?
>
For that reason, it is not possible to have to constructors with the
same number and type of parameters. The compiler will report something
like:
ambiguous function overloading: Date::Date(int, int, int)
thanks,
--
Mikhail
More information about the cs13001
mailing list