knutson@hsinchu.sw.mcc.com (Jim Knutson) (07/31/89)
What does this construct mean and where does it come from?
class multi_v {
public:
vect a, b, c;
multi_v(int i):a(i), b(i), c(i) { }
// ^^^^^^^^^^^^^^^^^
};
It appears in Ira Pohl's book "C++ for C Programmers". I've looked
everywhere for a description of this syntax and can't find one. It's
described in Pohl's book either.
Jim Knutson
knutson@mcc.com
cs.utexas.edu!milano!knutson
--
Jim Knutson
knutson@mcc.com
cs.utexas.edu!milano!knutson
brucec@demiurge.WV.TEK.COM (Bruce Cohen;685-2439;61-028) (08/01/89)
In article <2701@hsinchu.sw.mcc.com> knutson@hsinchu.sw.mcc.com (Jim Knutson) writes: >What does this construct mean and where does it come from? > >class multi_v { >public: > vect a, b, c; > multi_v(int i):a(i), b(i), c(i) { } > // ^^^^^^^^^^^^^^^^^ >}; That's the way to pass arguments to the constructors of the member objects a, b, and c, so they are constructed before the containing object. This is described in Stroustrup, pp. 159-161. Bruce Cohen brucec@orca.wv.tek.com Interactive Technologies Division, Tektronix, Inc. M/S 61-028, P.O. Box 1000, Wilsonville, OR 97070
jima@hplsla.HP.COM (Jim Adcock) (08/02/89)
>class multi_v { >public: > vect a, b, c; > multi_v(int i):a(i), b(i), c(i) { } > // ^^^^^^^^^^^^^^^^^ >}; Its in Lippman somewhere -- that's where I first noticed it. If you want to allow constant objects to be created, this is the technique you should use. The comma part is the initialization section. The brace part is construction: class vect { public: int i1, i2, i3; vect(int i) : i1(i), i2(i), i3(i) { } vect& operator=(int i) {i1=i; i2=i; i3=i; return *this;} }; class multi_v { public: vect a, b, c; multi_v(int i):a(i), b(i), c(i) { } }; const multi_v mv(5); //multi_v works class bogus_v { public: vect a, b, c; bogus_v(int i) {a=i; b=i; c=i;} }; const bogus_v bv(5); //but bogus bombs Note: the comma initializer section works on built-in types too, not just user defined classes. In general, one is better off to move as much as possible out of the constructor section and into the initializer section. The initializer section can contain coercions and the like, so it is not limited to trivial initializations.