1

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?

quamrana
  • 37,849
  • 12
  • 53
  • 71
cong
  • 149
  • 1
  • Start reading a solid introductory book such as Accelerated C++ from Koenig&Moo – Umut Tabak May 06 '11 at 19:33
  • You can find a list of good introductory books here: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Robᵩ May 06 '11 at 19:53
  • constructor is only method to create the user defined object –  May 06 '11 at 20:52

7 Answers7

4

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.

Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • exactly, you could think of it as "calling the constructor" of member x with value xx. – buc May 06 '11 at 18:52
2

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • +1 For the link. I was actually searching for a thread on SO which explains **initializer lists** but in vain. I think once I have seen it which explains elaborately. – Mahesh May 06 '11 at 18:59
1

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;

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
0

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

Jeff Linahan
  • 3,775
  • 5
  • 37
  • 56
0

That's a constructor with an initializer.

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

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
0

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

Boaz Yaniv
  • 6,334
  • 21
  • 30
0

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

charley
  • 5,913
  • 1
  • 33
  • 58