PDA

View Full Version : default parameters in constructor class



mickey
23rd February 2008, 18:11
hello, I've got one class constructor with two option parameter; so I can create the object like this:


Myobj::Myobj( char* parone="", char* partwo="") :
_name(parone), _value(partwo) {........}

Myobj obj(); // in this case warning
Myobj obj("one", "two"); //this ok.

//warning is: prototyped function not called (was a variable definition intended?)

I suppose that to using default parameters is necessary has first parameters not default. Is this? Anyway: I'd like avoid a second constructor because I had to duplicate its contents (and It could be large). Ideas?

THanks..

jpn
23rd February 2008, 18:23
Myobj obj;

mickey
23rd February 2008, 18:34
in that way compiler gets:
error: no appropriate default constructor available

jpn
23rd February 2008, 18:37
The default parameter values should be defined in the header file, not in .cpp file.

Michiel
23rd February 2008, 19:44
Be also aware that the default parameter method allows someone to call your constructor with just the first parameter filled in. If you want to have either both or none specified, you need two constructors. You can delegate the construction process to another function, so you won't have code duplication.