Function overloading: Difference between revisions

Content deleted Content added
ddd
Tag: Reverted
m Reverted edits by 78.151.16.99 (talk) (AV)
Line 89:
</syntaxhighlight>
 
By overloading the constructor, one could pass the tip and total as parameters at creation. This shows the overloaded constructor with two parameters. This overloaded constructor is placed in the class as well as the original constructor we used before. Which one gets used depends on the number of parameters provided when the new Bill object is created (none, or two):
 
<syntaxhighlight lang=Cpp>
Bill(double tip, double total)
: tip(tip),
total(total)
{ }
</syntaxhighlight>
 
Now a function that creates a new Bill object could pass two values into the constructor and set the data members in one step. The following shows creation and setting the values:
 
<syntaxhighlight lang=Cpp>
Bill cafe(0.10, 4.00);
</syntaxhighlight>
 
This can be useful in increasing program efficiency and reducing code length.
 
Another reason for constructor overloading can be to enforce mandatory data members. In this case the default constructor is declared private or protected (or preferably deleted since [[C++11]]) to make it inaccessible from outside. For the Bill above total might be the only constructor parameter{{snd}} since a Bill has no sensible default for total{{snd}} whereas tip defaults to 0.15.
 
==Complications==