Thread: Correct synthax for calling a constructor with a temporary object.

  1. #1
    Chinese pâté foxman's Avatar
    Join Date
    Jul 2007
    Location
    Canada
    Posts
    404

    Correct synthax for calling a constructor with a temporary object.

    Hi,

    I have a problem calling a constructor with a temporary object; the syntax makes the compiler think it's a function declaration where I only want to instantiate an object... here's a simplified example of what I would like to do...

    Code:
    class Test1
    {
    };
    
    class Test2
    {
    public:
        explicit Test2(const Test1 &)
        { }
    
        void function() const
        {
            return;
        }
    };
    
    int main()
    {
        Test2 t2(Test1());  // I want t2 to be a Test2 object, but this syntax
                            // means "t2 is a function returning a Test2 object
                            // and taking one argument who is a function returning a
                            // Test1 object and taking no argument
        t2.function();      // error: request for member ‘function’ in ‘t2’, which is
                            // of non-class type ‘Test2 ()(Test1 (*)())’
    
    
        return 0;
    }
    What is the correct syntax to achieve this ?

    Thanks
    I hate real numbers.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Code:
    Test2 t2((Test1()));

  3. #3
    Chinese pâté foxman's Avatar
    Join Date
    Jul 2007
    Location
    Canada
    Posts
    404
    Hahaha. Thanks. I have been scared for a few moment.
    I hate real numbers.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    It certainly is a weird quirk of the language.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 01-23-2008, 06:21 AM
  2. Function argument not converted to reference
    By MWAAAHAAA in forum C++ Programming
    Replies: 14
    Last Post: 10-22-2006, 03:24 AM
  3. Temporary object destruction
    By Mortissus in forum C++ Programming
    Replies: 2
    Last Post: 07-05-2006, 06:47 AM
  4. returning a temporary class object
    By nextus in forum C++ Programming
    Replies: 3
    Last Post: 01-31-2003, 03:54 PM