Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!zaphod.mps.ohio-state.edu!uwm.edu!bionet!apple!netcom!teda!ditka!mcdchg!tellab5!balr!clrcom!rmartin From: rmartin@clear.com (Bob Martin) Newsgroups: comp.lang.c++ Subject: Re: Initializing a Member That is a Class Message-ID: <1991Feb4.154627.15167@clear.com> Date: 4 Feb 91 15:46:27 GMT References: <1991Jan31.194631.3447@persoft.com> Distribution: na Organization: Clear Communications, Inc. Lines: 44 In article <1991Jan31.194631.3447@persoft.com> eda@persoft.com (Ed Almasy) writes: >This has been puzzling me for some time, and I'm hoping that someone >here can explain it. > >Assuming: > A is a class, with a constructor that requires 3 arguments > B is a class, containing a member of type A > C is a struct, containing a member of type A > >My question is: When I create data items of type B or C, where do the >constructor arguments for the member that is of type A come from? Do I >have to put them in my declaration for B or C, or is there a way to >specify them at run time? If so, what is the proper syntax? > Refer to ARM 12.1 concerning constructors and 12.6.2 concerning member initialization. You can proceed in one of two ways. Either create a "default constructor" for class A. (You must do this since the compiler wont do it for you if you have declared other constructors for A). Then when B or C are constructed the default constructor will be used for A. Or you can provide the Constructors of B and C with member initialization lists which will construct A for you. You can specify all 3 parameters in the member intialization list. class B { A theA; }; // B constructor. B::B(a,b,c) : theA(a,b,c) // <- member intialization list { ... code for B construction } -- +-Robert C. Martin-----+:RRR:::CCC:M:::::M:| Nobody is responsible for | | rmartin@clear.com |:R::R:C::::M:M:M:M:| my words but me. I want | | uunet!clrcom!rmartin |:RRR::C::::M::M::M:| all the credit, and all | +----------------------+:R::R::CCC:M:::::M:| the blame. So there. |