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

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

 



Michael Gong schrieb:
> Hi, all,
> 
> Thanks for the explanation. After google it, it looks like the explicit
> type conversion also works on user-defined type.

Yes, it is basically creating a new instance of some type by
constructing it. No more, no less.
Unless a constructor has been declared with the "explicit" keyword C++
applies this type conversion even implicitly if required:

struct Bar{};
struct Baz{};

struct Foo{
  Foo(const Bar&);
  explicit Foo(const Baz&);
};

void f( Foo );

int main() {
  Bar bar;
  Baz baz;

  f( bar ); // works, as compiler implicitly generates f(Foo(bar))
  f( baz ); // does not work, compiler is forbidden to use constructor
            // for implicit type conversions

  f( Foo( baz ) ); // works, we invoke constructor explicitly
}

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

In the int('A') example it is the copy-constructor. The compiler
provides automatically generated default- and copy-constructors for any
type that has no user-defined constructor.

If some constructor is defined explicitly, copy- and default-constructor
are no longer generated by the compiler. Your Point class therefore has
*no* default-constructor.


>  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 */
> }
>

Daniel

[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