This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: C++ question: where does int() come from ?


Hi, all,

Thanks for the explanation. After google it, it looks like the explicit type conversion also works on user-defined type.

Meanwhile, to be more correct, I think it is not a "copy-constructor" , but just a constructor call. For example:

class Point {
   private :
       int x, y;
   public:
       Point(int x_, int y_) {
           cout << "default constructor" << "\n";
       }

       Point(const Point& p) {
           cout << "copy constructor" << "\n";
       }
};

int main() {
       Point(3, 4);        /* it will call the default constructor */
}


Regards,


Mike



----- Original Message ----- From: "John (Eljay) Love-Jensen" <eljay@adobe.com>
To: "Daniel Lohmann" <daniel.lohmann@informatik.uni-erlangen.de>
Cc: <gcc-help@gcc.gnu.org>
Sent: Wednesday, December 20, 2006 7:26 AM
Subject: RE: C++ question: where does int() come from ?



Hi Daniel,


Actually it is not a "constructor cast", but a constructor call. In C++, even the built-in types (such as int, double, ...) have a default- and a copy-constructor.

int(<some integer expression>) invokes the copy-constructor for the int type, resulting in a (temporary) int instance. The type conversion ("cast") is performed even before that:'A' is (by integer promotion) implicitly extended to an int while being passed to the copy-constructor.

Sounds good to me. As a devout pedant, I appreciate the clarification.


The idiom of using int('A') was called a "constructor cast" by my C++ co-workers, so the (regional?) terminology for that pattern is what I was describing. And that terminology goes back to at least 1995, to my earliest recollection of its usage.

A quick Google of "constructor cast" pulls up a few (~30) pages which mention that pattern. So it appears that the terminology for the pattern isn't widespread throughout the C++ community. Just a smattering. As far back as 2001.

Hmm, in one spot, the term "coercion cast" is also used for that pattern.

Assuming one of the Google pages is correct, the standard calls it "explicit type conversion (functional notation)".

Apparently -- as you pointed out -- it is not (literally) a cast, so calling it a "constructor cast" is a bit of a misnomer along the lines of calling bald a hair color.

Caveat - a "constructor cast" is only good for making rvalues.

Sincerely,
--Eljay


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]