0

recently I found a bug in my program caused by adding extra parentheses.

Following is my code. The program print nothing but "end main"

#include <stdio.h>

class A
{
public:
    A()
    {
        printf("init\n");
    }
    A(A& a)
    {
        printf("copy constructor");
    }
    ~A()
    {
        printf("finit\n");
    }
};

int main()
{
    A a();
    printf("end main\n");
}

But when I remove parentheses in the the main function, it prints "init", "finit" and "end main", this is what I want.

    int main()
    {
        A a;
        printf("end main\n");
    }

Could anyone tell me why? I compiled the code in VS2013 and gcc4.7.2, the results are same.

Yiting
  • 19
  • 1
  • It's a side effect of C++ parsing rules; see the linked question (and dozens of others on Stack Overflow) for more information. – Jonathan Potter Dec 14 '15 at 04:30
  • https://stackoverflow.com/questions/17713124/what-does-a-a-mean?lq=1 may have been a better dupe... but there are many. – Jonathan Potter Dec 14 '15 at 04:31
  • The line `A a();` is a declaration of a function a that takes no arguments and returns an object of type A. There is no object there, for your code to invoke A's constructor or destructor. – Happy Green Kid Naps Dec 14 '15 at 04:32

0 Answers0