0

I was trying something around default constructor and stumbled upon this kind of situation


static int e = 0;
class X
{
public:
    X()
    {
        e = 10;
    }
    ~X()
    {
        e = 11;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    if(e ==   88) return 88;
    X a();
    printf("%d", e);
    return 0;
}

The output of above code when compiled on visual studio 2010 with default optimisation parameter is 0. Constructor and destructor of X completely gets ignored.

When I change code to

int _tmain(int argc, _TCHAR* argv[])
{
    if(e ==   88) return 88;
    X a = X();
    printf("%d", e);
    return 0;
}

I get expected output that is 10

I wan't to understand why 1st code doesn't works and 2nd does work?

Shubham
  • 172
  • 8
  • 7
    This is unrelated to optimizations. `X a();` declares `a` as a function taking no arguments and returning an `X` object by value. It's as simple as that. Use plain `X a;` for a default-constructed `X` object named `a`. – Some programmer dude Aug 02 '22 at 08:40
  • @Shubham See [What's the difference between type name() and type name = type()?](https://stackoverflow.com/questions/72434416/whats-the-difference-between-type-name-and-type-name-type) – Jason Aug 02 '22 at 08:49
  • The possibility to use braces for initialization, `X a{};` was added partially because of this. With braces it can never be a function. – BoP Aug 02 '22 at 09:55
  • In the early design of C++, the decision was made that `X a(void);` no-parameter function declaration could be expressed as `X a();` (There is some cross-over with **C** history, too, which has it's only interesting journey & evolution.) One result of that is `X a();` is interpreted as a function declaration, instead of a local variable with default initialization. C++11 added `X a{};` for default construction (in particular, for member variable declarations), but the common practice is `X a;` for local variables. – Eljay Aug 02 '22 at 13:41

0 Answers0