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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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@xxxxxxxxx>
To: "Daniel Lohmann" <daniel.lohmann@xxxxxxxxxxxxxxxxxxxxxxxxxx>
Cc: <gcc-help@xxxxxxxxxxx>
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 of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux