4 ms·
Perhaps my terminology is off, but as a minor nitpicking point I have never heard of this type of constructor refered to as a copy constructor. A copy construc
by ryanmolden 14y ago
Perhaps my terminology is off, but as a minor nitpicking point I have never heard of this type of constructor refered to as a copy constructor. A copy constructor is a constructor for type Tthat takes an existing T and initializes the new T to have the same underlying state. So something like
class Foo
{
public:
Foo(const Foo& other)
{
//copy state from other Foo here
}
};
What this example is talking about is a normal constructor that can be (perhaps unintentionaly) used in the context of an implicit conversion, so something like
class Foo
{
public:
Foo(int heyThere)
{
}
};
This allows the C++ compiler to create an automatic conversion (in some instances) from int -> Foo simply by inserting a call to this constructor. So it can cause code like this to compile even if it was not intended
void HandleTheFoo(const Foo& theFoo)
{
//Do something here
}
void SomeMethod()
{
Foo intended; //assume there is a default ctor available even though I didn't show it above
int whoops = 5;
HandleTheFoo(whoops);
}
Marking the constructor explicit prevents the compiler from using it in an implicit conversion context.
- raganwald 14y agoI’ve heard it that implicit conversion is a specialization of copy construction. So you can still use explicit Foo (const Foo& other) if you wish to force all construction of Foos to use the new keyword and not to be passed by value. But I’m certainly willing to accept the suggestion that the two are distinct, in which case my understanding is that the explicit keyword blocks implicit conversion (as described in the story and in your example) and I understand that it also blocks implicit copy construction.
- ryanmolden 14y agoAh, that makes sense. Though technically you don't have to use the new keyword unless you want a heap allocated instance, something like HandleTheFoo(Foo(5)); or even HandleTheFoo(Foo(otherFoo)); is perfectly cromulent with the constructor being marked explicit. But that is just me engaging in terminological quibbling, I get what you meant/said in spirit and don't disagree that people asking questions they don't have a deep understanding of themselves can only lead to fail.
- raganwald 14y agoThanks for the kind words. And the reminder about stack variables!!! I wasn’t trying to suggest that Ted didn’t have deep knowledge of C++, as we can see his fictional knowledge is far better than my distant memories. I was trying to suggest that he was engaging in copy-and-paste interviewing, and that it’s a bad idea for all of the same reasons copy-and-paste coding is a bad idea :-)
- evincarofautumn 14y agoRight. The term is “conversion constructor”, one that can be called with a single argument and is not declared “explicit”.
- raganwald 14y agoThanks! “Given enough eyeballs, all essay problems are shallow."