A Question about explicit constructor

This is a discussion on A Question about explicit constructor within the C++ Programming forums, part of the General Programming Boards category; Code: class Test{ private: int b; public: explicit Test(int x=0):b(x){} explicit Test (const Test& ts):b(ts.b){} }; int main(){ Test ts=static_cast<Test>(1);//It's ...

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    284

    A Question about explicit constructor

    Code:
    class Test{
    private:
    	int b;
    public:
    	explicit Test(int x=0):b(x){}
    	explicit Test (const Test& ts):b(ts.b){}
    };
    
    int main(){
    
    	Test ts=static_cast<Test>(1);//It's OK here
    	Test ts2=static_cast<Test>(ts);// what's wrong here?
           
    return 0;
    }
    What's wrong with the code? Why can't it be compiled?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Neither is OK for my compiler.

    The aim of explicit keyword is to allow only constructs like that:
    Code:
    Test ts(1);
    Test ts2(ts);
    And to avoid situations like that
    Code:
    void foo(Test t);
    ...
    foo(2); //OK without explicit
    In other words, explicit makes the compiler stricter, and you should not use it to devise workarounds with funny casts.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Default Constructor Question
    By NoviceC in forum C++ Programming
    Replies: 6
    Last Post: 09-28-2008, 02:12 AM
  2. Copy constructor question
    By BigFish21 in forum C++ Programming
    Replies: 9
    Last Post: 05-04-2008, 12:18 PM
  3. How do I override constructor in inheritance?
    By Loduwijk in forum C++ Programming
    Replies: 13
    Last Post: 03-24-2006, 08:36 AM
  4. question regarding consrtuctor calls
    By alt234 in forum C++ Programming
    Replies: 4
    Last Post: 12-12-2005, 02:13 PM
  5. another exercise question
    By luigi40 in forum C# Programming
    Replies: 3
    Last Post: 11-28-2005, 02:52 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21