explicit copy constructor

D

denis

Hello,

I noticed the following in the "C++ Coding Standards" book. Why should
the code
on line 30 be in error?

Transmogrify accepts a (B obj), and we are passing it a B obj. I
understand why
the other call to transmogrify failed: we disallowed implicit
conversion D->B
with a keyword 'explicit'. Or, does the call Transmogrify( b ); mean
that a
copy constructor still gets invoked - implicitly (which is what
explicit is supposed
to disallow)?

Thank you very much.

10 // Making the copy constructor explicit (has side effects, needs
improvement)
11 class B {// ...
12 public:
13 explicit B( const B& rhs );
14 };
15
16 class D : public B {/* ... */};
17
18
19 Calling code can still slice if it really wants to, but has to
be, well, explicit about it:
20
21 void Transmogrify( B obj ); // note: now can't ever be
called (!)
22 void Transmogrify2( const B& obj ) { // an idiom to explicitly
say "I want to take
23 B b( obj ); // obj by value anyway (and
possibly slice it)"
24 // ...
25 }
26
27 B b; // base classes shouldn't be concrete (see
28 D d; // Item 35), but let's imagine that B is
29
30 Transmogrify( b ); // now an error (or should be; see note)
31 Transmogrify( d ); // now an error (or should be; see note)
32 Transmogrify2( d ); // ok
33
34 Note: As of this writing, some compilers incorrectly accept one
or both of these calls to transmogrify. This idiom is standard, but
it's not (yet) completely portable
 
I

Ian Collins

denis said:
Hello,

I noticed the following in the "C++ Coding Standards" book. Why should
the code
on line 30 be in error?

Transmogrify accepts a (B obj), and we are passing it a B obj. I
understand why
the other call to transmogrify failed: we disallowed implicit
conversion D->B
with a keyword 'explicit'. Or, does the call Transmogrify( b ); mean
that a
copy constructor still gets invoked - implicitly (which is what
explicit is supposed
to disallow)?
Yes, the call passes a B by value and B's copy constructor is declared
explicit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,733
Latest member
LonaMonzon

Latest Threads

Top