0
#include <iostream>

class SomeClass {
 public:
    SomeClass(): something(100) {
        std::cout<<"constructing"<<std::endl;
    }

    ~SomeClass() {
        std::cout<<"destructing"<<std::endl;
    }

    void printSomething() {
        std::cout<<something<<std::endl;
    }
    int something;
};

int main(int argc, char * argv[]) {
    SomeClass(instSomeClass);
    instSomeClass.printSomething();
    return 0;
}

Whilst scrolling through some code the other day I came across something which I haven't seen before and don't fully understand. The example above, which compiles and runs, is similar and seems to declare and initialize an object using a notation which I didn't think was legal: SomeClass(instSomeClass); I expected an 'instSomeClass undeclared' error or something similar.

Whats going on here? I assume the compiler is interpreting this as something like: SomeClass instSomeClass; or SomeClass instSomeClass = SomeClass();. I can't find any information on this online. Has anyone else seen this syntax that can explain? What is this called?

Teivaz
  • 5,462
  • 4
  • 37
  • 75
gb12345
  • 29
  • 3
  • 1
    See [dcl.meaning#6](http://eel.is/c++draft/dcl.meaning#6): "Parentheses do not alter the type of the embedded *declarator-id*, but they can alter the binding of complex declarators." – uh oh somebody needs a pupper May 25 '16 at 18:21
  • Also: http://stackoverflow.com/questions/26832321/what-is-the-purpose-of-a-declaration-like-int-x-or-int-x-10 – NathanOliver May 25 '16 at 18:25
  • http://stackoverflow.com/questions/34417071/visual-studio-c-compiler-weird-behaviour/34417360#34417360 – marcinj May 25 '16 at 18:26
  • Regardless of the fact that it works, this is not a "good" way to code for precisely the reason you are asking this on SO ;) – Conduit May 25 '16 at 18:27
  • 2
    `SomeClass(instSomeClass);` is the same as `SomeClass instSomeClass;`. – R Sahu May 25 '16 at 18:27
  • @orbitcowboy I think you might want to check that. Take the above code, add a copy constructor, run, and see what you get. – user4581301 May 25 '16 at 20:27

0 Answers0