Article View: comp.std.c++
Article #1915Re: Explicit-keyword and default constructors
From: Steve Clamage
Date: Tue, 05 Sep 1995 16:14
Date: Tue, 05 Sep 1995 16:14
65 lines
2404 bytes
2404 bytes
In article 1m9@proffa.cc.tut.fi, p150651@proffa.cc.tut.fi (Pulkkinen Esa) writes:
>
>Consider this example:
>
>class A
>{
>public:
> explicit A() {}
>};
>A a; // Legal? (IMHO: no)
Legal.
>A b=A(); // OK, as always
Yes.
>A c(); // OK, c is a function returning A :)
Yes.
>
>class B : public A {}
>// Default constructor generated, and calls A()? Legal?
>// (IMHO: no)
Legal.
I don't think placing "explicit" on other than a one-argument constructor
has any effect. By "one-argument constructor" I mean one which may be
invoked with one argument; it might have additional arguments with default
values. The only discussion of the "explicit" keyword that I can find
in the draft standard concerns only one-argument constructors.
A one-argument constructor is a type conversion from the argument type
to the class type. Such a public constructor may be used implicilty by
the compiler whenever that conversion is required.
The "explicit" keyword prevents using a one-argument constructor for
implicit type conversion. All explicit uses of the constructor are still OK.
Example:
class A {
public:
explicit A(int);
};
foo(const A&);
...
foo(3); // error
The call to foo would be OK if A were not marked "explicit". The compiler
would generate an implicit conversion of an "int" to an "A". But the
marked constructor cannot be used for that purpose. Similarly:
A a(3); // OK, explicit
a = A(4); // OK, explicit conversion, then assignment
a = 5; // error, can't convert "int" to "A" implicitly
---
Steve Clamage, stephen.clamage@eng.sun.com
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Technical Details
Message-ID:
<42hrhr$51j@engnews2.Eng.Sun.COM>Path:
arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!taumet!clamageReferences:
<42gjou$1m9@proffa.cc.tut.fi>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!taumet!clamage From: clamage@Eng (Steve Clamage) Newsgroups: comp.std.c++ Subject: Re: Explicit-keyword and default constructors Date: 5 Sep 1995 16:14:31 GMT Organization: Sun Microsystems Inc. Approved: clamage@eng.sun.com (comp.std.c++) Message-ID: <42hrhr$51j@engnews2.Eng.Sun.COM> References: <42gjou$1m9@proffa.cc.tut.fi> Reply-To: clamage@Eng NNTP-Posting-Host: taumet.eng.sun.com Content-Type: text X-Nntp-Posting-Host: taumet.eng.sun.com Content-Length: 1569 X-Lines: 61 Originator: clamage@taumet