quote:Original post by Mayrel
1) Calling a plain constructor is perfectly valid outside of a constructor. [5.2.3]
Yeah, but you make it sound like a constructor is just another function, which it''s not. You''re not just calling a function, you''re creating a temporary object too. ''Calling'' a constructor is just creating an object with syntax that looks like a function call.
quote:2) Calling a plain constructor inside a constructor for the same class is probably invalid because that''d result in an infinite loop. [Although I couldn''t see any rule against it in the standard.]
Yeah, but that''s not the problem in this case. You could be using something other than Foo and it would still not work. The problem here is that you''re simply getting the syntax wrong
More specifically, trying to initialise something that isn''t initialisable.
quote:3) As it happens, C++ considers a plain Foo(x) to be a definition of a Foo named x, rather than an instantiation of Foo using x as the parameter. In the middle of an expression, it does the right thing.
No - it considers ''Foo(x)'' to mean ''initialise the member object or base class called Foo with the value of x, as if the member or base class called Foo had its constructor called with x as the parameter. Since the object in question (the instance of Foo being constructed) has no member or base class called Foo (it IS Foo, it doesn''t contain Foo in any form), then it doesn''t work.
Basically, you can''t ''call'' one constructor from another, because they''re not simple functions like that.
To (pretty much) do what you intended, you need to separate out the construction from initialisation functions. Write one function to initialise the int stuff, one for the char* stuff, and call the relevant initialisers in the relevant constructors. That saves you the code duplication. It won''t save you duplicate constructions (although that won''t be an issue with basic data types as used here).
And to the poster who asked what the point of private constructors was: it stops people declaring instances of that object. You can then control access to creating that object via a static member function. One use of this would be to only create a given number of such objects, and enforce that restriction.