2

Why A a(); won't call constructor? and why sizeof(C) is 1?

class C
{
public:
    C(){ 
        cout << "C default" << endl; 
    }
};

int main() {
    C a();
    cout << sizeof(C) << endl;
    return 0;
}

does “C a();” become a function Statement?

Shuaizi
  • 51
  • 5

2 Answers2

5
C a();

That doesn't create an instance of C called a, that declares a function called a which takes no arguments and returns a C.

To get what you want you have two main options:

C a;
C a{}; //c++11

sizeof(C) is 1 because every object in C++ takes up at least one byte, even if nothing meaningful is stored there. Think about if you had an array of C; if sizeof(C) was 0, c_array[0] would be at the same address as c_array[10]. C++ doesn't allow two distinct objects to have the same address.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
-1

1.If you want to call the constructor when a new object be created, The code should like this:

C a;

C *a = new C();

2.Because no object shall have the same address in memory as any other variable.

So if the class or struct has no variables or functions, sizeof(class) = 1.

gdreamlend
  • 108
  • 9