开发者

a question about constructor in c++

开发者 https://www.devze.com 2023-03-03 04:52 出处:网络
I am newbie to c++, I have not yet seen this kind of constructor, w开发者_C百科hat does it do? class A {

I am newbie to c++, I have not yet seen this kind of constructor, w开发者_C百科hat does it do?

class A {
    int x;
public:
    A(int xx):x(xx) {}
};

int main() {
    A a(10);
    A b(5);
    return 0;
}

Is the code above valid?

What does this constructor do? A(int xx):x(xx) means what? A cast?


is the code above valid?

Yes.

what does this constructor do? A(int xx):x(xx) means what?

It is called initializer list which copies xx to the class member x.


The stuff after the : and before the body (the empty braces) is an initializer list. It initializes the member variable x with xx.

See this section from the C++ FAQ: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6.


The string :x(xx) is called an initializer. As you can see it's valid on only a constructor. The effect is to initialize x with the value xx. So your code makes two A objects - one has an x of 10 and the other of 5.

This is more efficient than letting it be initialized and then changing its value in the body of the constructor by writing x=xx;


That is called an initialization list. The private variable x will be initialized with xx when the constructor is called.


That's a constructor with an initializer.

The x(xx) initializes x with the value of xx


A(int xx) : x(xx) initializes the data member x with the value of xx.


The code is valid: The member variable "x" is being set a value in the "base/member initializer list".

This type of initialization is required when you are initializing a value for a reference member, constant member, or to forward arguments to the base constructor.

It is optional in other cases, like this one, where the value could have been explicitly set in the constructor body (but this is arguably faster, since it is initialized as memory is allocated).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号