does POD class object initialization require const

2019-08-10 21:02发布


I read following links :-

object initialized with and without parentheses

types of default constructor

diff b/w value,zero and default intilization

I have some question which i want to clarify.


1) Given a POD class , say :-

class A{
        int val;
};


If i create an object of type A.

A obj; // will this call implicitly defined constructor provided by compiler ?
Now as far as my understanding in this case constructor is not called.is it correct?

new A(); // value-initialize A, which is zero-initialization since it's a POD. Now in this case will implicitly defined constructor provided by compiler ? Is there is any role of constructor for zero initializing the object?

If my understanding is wrong , could you please give me an example where implicitly defined defined constructor is not called at all.

Thank you in advance.

2条回答
做自己的国王
2楼-- · 2019-08-10 21:53

1) Correct. obj.val is not initialized.

2) This is a function declaration, not an initialization:

A obj(); // function obj() returning an A

If you did this,

A obj{};     //C++11
A obj = A(); // C++03 and C++11

obj would be value-initialized, and so would obj.val. This in turn means that obj.val would be zero-initialized (value-initialization means zero-initialization for built-in types).

查看更多
地球回转人心会变
3楼-- · 2019-08-10 21:53
A obj;

It calls default constructor (or even not for optimization), however default constructor doesn't initialize it.

 

A obj();

It's a function declaration. No arguments and returns A.

 

A obj{};

Instead, you can use above code which sets val to zero.

查看更多
登录 后发表回答