Reputation: 35982
class A {};
class B
{
public:
B(const A& a, int i = 10) : m_a(a), m_i(i) {}
private:
int m_i;
A m_a;
};
B getB(void)
{
//return B(A()); // Method one
//return A(); // Method two
}
Both method one and method two pass the compilation of VS2010.
Question 1> Which one is better?
Question 2> Is it true that an implicit constructor supports more than one pass-in parameters if all except the first parameters have default values?
Thank you
Upvotes: 2
Views: 82
Reputation: 477188
I would decorate the constructor as explicit
, and then use method one as the only available method:
class B {
public:
explicit B(A const & a, int b = 10) : m_a(a), m_i(b) { }
// ...
};
B foo() { return B(A()); }
That way you can never accidentally construct a B
from an A
. If the constructor of B
is expensive or may throw, then having this extra level of deliberateness in your code may well help make it more readable and less error-prone.
Upvotes: 1
Reputation:
Both are correct. First one explicitly creates B
instance, and the second one implicitly creates B
from A
. I like neither of those. They just increase confusion level and nothing more.
Upvotes: 1
Reputation: 106569
Both are valid and both do the same thing. I'd use the first one because I find the second one confusing, but different strokes for different folks.
EDIT: Actually, I'd do even more than that. I'd mark B
's constructor as explicit
in order to prevent just the sort of thing that makes the second one compile.
Note: I would avoid use of (void)
in method signatures in C++.
Upvotes: 2