Thread: A Question about explicit constructor

  1. #1
    Registered User
    Join Date
    Apr 2007

    A Question about explicit constructor

    class Test{
    	int b;
    	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
    Neither is OK for my compiler.

    The aim of explicit keyword is to allow only constructs like that:
    Test ts(1);
    Test ts2(ts);
    And to avoid situations like that
    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, 09:36 AM
  4. question regarding consrtuctor calls
    By alt234 in forum C++ Programming
    Replies: 4
    Last Post: 12-12-2005, 03:13 PM
  5. another exercise question
    By luigi40 in forum C# Programming
    Replies: 3
    Last Post: 11-28-2005, 03:52 PM