CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Aug 2006
    Location
    Timisoara, Romania
    Posts
    433

    What is the difference between these object instantiation methods?

    What is the difference between these object instantiation methods:

    1.
    Code:
    ClassName ObjectName;
    2.
    Code:
    ClassName ObjectName();
    Is there any?

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: What is the difference between these object instantiation methods?

    The latter declares a function that takes no arguments and returns a ClassName.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    Re: What is the difference between these object instantiation methods?

    Quote Originally Posted by Feoggou View Post
    What is the difference between these object instantiation methods:
    There is no instantiation going on in the second method. That's a function declaration.

    See here:
    Code:
    #include <string>
    
    int main()
    
    struct ClassName
    {
    };
    
    ClassName ObjectName();  // declare function
    
    int main()
    {
        ClassName theName;
        theName = ObjectName();
    }
    
    
    // here is the function impelemtation
    ClassName ObjectName()
    {
       return ClassName();
    }
    See the code in red?

    Regards,

    Paul McKenzie

  4. #4
    Join Date
    Jun 2009
    Location
    oklahoma
    Posts
    199

    Re: What is the difference between these object instantiation methods?


  5. #5
    Join Date
    Aug 2006
    Location
    Timisoara, Romania
    Posts
    433

    Re: What is the difference between these object instantiation methods?

    thanks a lot.

    It seems that if you have a class defined like this:
    Code:
    class ClassName
    {
         int x;
    public:
        ClassName()
       {
           x = 3;
       }
    };
    you can use either this:
    Code:
    ClassName obj;
    or this:
    Code:
    ClassName obj();
    And I was saying to myself: there can't be any difference!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured