c++ - default constructor that has the option to take in a parameter? -


is possible have 1 constructor have option of being default constructor if parameter not passed in.

example, instead of having 2 constructors, 1 default constructor , constructor initializes numbers passed in, possible have 1 constructor if value passed in, set value member function, , if no value passed in, set member function number.

example:

weight.h file:

   class weight { public:     weight() { size = 0; }     weight(int a) : size(a) {}      int size; }; 

main.cpp file:

int main(void) {   weight w1;   weight w2(100); } 

i've been working on different school projects , require have different types of constructors, , i'm wondering if there way have once saves time. help.

yes, constructor parameter may have default argument, other functions can. if of parameters of constructor have default arguments, constructor default constructor. so, example,

class weight { public:      explicit weight(int = 0) : size(a) { }      int size; }; 

this constructor may called single argument or no arguments; if called no arguments, 0 used argument a parameter.

note i've declared constructor explicit. if have constructor may called single argument, should declare explicit prevent unwanted implicit conversions occurring unless want constructor converting constructor.

(if aren't familiar yet converting constructors or implicit conversions, that's okay; following rule sufficient of code you'll ever write.)


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -