On 2008-03-31 18:50, Onix wrote:
> I'm reading a code and this is what it looks like, pretty strange for
> me:
>
> class A {
> size_t i_;
> public:
> A(size_t i): i_(i) {}
> }
>
> Is the constructor above is the same with the following?
>
> A(size_t i) {
> i_ = i;
> }
No, in the first case the value of i_ will be set _before_ entering the
constructor, while in the second case the value of i_ will be
undetermined when the constructor is created.
The first case uses an initialisation list which are very useful things,
learn to use them because sometimes you have to. Examples of these
cases are when you have const members:
class A {
const size_t i_;
public:
A(size_t i): i_(i) {} // Sets the value of i_
};
or when you derive from a class with a constructor that takes one or
more arguments:
class Base {
public:
Base(int i) {}
};
class A : public Base {
public:
A(int i): Base(i) {} // Runs Base's constructor
};
See also
http://www.parashift.com/c++-faq-lit....html#faq-10.6
--
Erik Wikström