cong
cong

Reputation: 149

a question about constructor in c++

I am newbie to c++, I have not yet seen this kind of constructor, what 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?

Upvotes: 1

Views: 117

Answers (7)

Kate Gregory
Kate Gregory

Reputation: 18974

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;

Upvotes: 1

charley
charley

Reputation: 5949

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).

Upvotes: 0

Boaz Yaniv
Boaz Yaniv

Reputation: 6424

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

Upvotes: 0

Yochai Timmer
Yochai Timmer

Reputation: 49261

That's a constructor with an initializer.

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

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272687

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.

Upvotes: 2

nahano
nahano

Reputation: 3835

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

Upvotes: 0

Mahesh
Mahesh

Reputation: 34625

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.

Upvotes: 4

Related Questions