(ref.doc)bs 250693

Next olavi 280693 Prev: brown 250693 Up: Usenet

From: [email protected] (Bjarne Stroustrup)
Newsgroups: comp.lang.c++
Subject: Re: Constructor Question!
Summary: it stands for initialization
Keywords: constructors
Date: 25 Jun 93 11:24:52 GMT
Organization: AT&T Bell Laboratories, Murray Hill NJ

[...]

The ``:name(expression)'' notation is used to initialize bases and members.
Thus, ``:item(t)'' initializes item with t.

For a built-in type such as int, ``:name(expression)'' isn't significantly
different from a an ordinary assignment ``name = expression'' in the body
of the constructor.

For references and constants we can't use assignment to get an initial value
so we need a specific notation for initialization.

For example:

	class X {
		int i;
		const int c;
		int& r;
	public:
		X(int& rr)
			:i(rr),	// initialize i by the value of rr
			 c(rr),	// initialize c by the value of rr
			 r(rr)	// bind r to the same int as rr
		{
			i = r;	// assign r to i, ok
			c = r;	// assign r to c, error: assignment to const
			r = rr;	// assign the value referred to by rr to the
				// int referred to by r
		}

As you can see, the meaning of the assignments and the initializations differ
in ways that makes the assignments useless as an alternative to initializatiion
for references and constants.

The main use of the ``:name(expression)'' notation is to provide arguments for
base classes. For example:

	class B { /* ... */ public: B(); B(int); /* ... */ };
	
	class D : public B {
		// ...
		D(int i) : B(i) { /* ... */ }  // use B(int) constructor
		D() { /* ... */ }   // use default B() constructor
		// ...
	};


automatically generated by info2www version 1.2.2.8