newbie question about constructor

Discussion in 'C++' started by sam, Dec 29, 2006.

  1. sam

    sam Guest

    Hi,
    Why declare constructors implicit or explicit ,whats the use of it?
    sam, Dec 29, 2006
    #1
    1. Advertising

  2. sam

    Guest

    , Dec 29, 2006
    #2
    1. Advertising

  3. sam

    Rolf Magnus Guest

    sam wrote:

    > Hi,
    > Why declare constructors implicit or explicit ,whats the use of it?


    Constructors that can be called with one argument are conversion
    constructors. If the constructor is not declared 'explicit', the compiler
    will do implicit conversions using that constructor.

    struct X{};
    struct Y{};

    class MyClass
    {
    public:
    MyClass(X);
    explicit MyClass(Y);
    };

    void myfunc(MyClass);

    int main()
    {
    X x;
    Y y;

    myfunc(x); // ok, conversion constructor is implicitly used
    myfunc(y); // error, constructor is explicit
    myfunc(static_cast<MyClass>(y)); // ok, explicit conversion
    }

    Btw: What C++ book are you reading that doesn't explain this?
    Rolf Magnus, Dec 29, 2006
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Giulio
    Replies:
    9
    Views:
    1,028
    Patrick Kowalzick
    Jun 25, 2003
  2. Brett Irving
    Replies:
    3
    Views:
    3,319
    John Harrison
    Jun 29, 2003
  3. Replies:
    6
    Views:
    1,100
  4. Replies:
    6
    Views:
    490
  5. Generic Usenet Account
    Replies:
    10
    Views:
    2,197
Loading...

Share This Page