Re: Default constructors, passing argument
From: Peter (peter_at_peter.com)
Date: 07/09/04
- Next message: Chad J McQuinn: "Re: Default constructors, passing argument"
- Previous message: Peter: "Re: Default constructors, passing argument"
- In reply to: Chris Newton: "Re: Default constructors, passing argument"
- Next in thread: jeffc: "Re: Default constructors, passing argument"
- Reply: jeffc: "Re: Default constructors, passing argument"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 9 Jul 2004 01:17:53 +0000 (UTC)
On Thu, 8 Jul 2004 21:07:58 +0000 (UTC), Chris Newton wrote:
> Peter wrote...
>> I have a subclass derived from another class as a member of my class. It
>> has a default constructor with the initialiser list used to pass values
>> common to each object.
>
>> The way the class works, it needs values from its owner class supplied to
>> it on initialisation. For example,
>>
>> class Thing {
>> private:
>> int val;
>> MySubClassObject hello; //constructed but needs val
>>
>> public:
>> Thing(int value) {
>> val = value; //value got too late
>> }
>> };
>>
>> What are the options?
>
> Do you mean that you want to supply the value of val to the constructor
> for hello?
Yes, at the same time as Thing is constructed I need MySubClass to get the
same argument.
>If so, you can't use the default constructor for
> MySubClassObject, because you need to pass the extra information in.
> hello being a member of your Thing class doesn't give it any special
> abilities to access the value of the val member of the Thing object to
> which it belongs.
>
> Does that answer your question?
Does that mean I cannot have it as a member var unless I make it a pointer
and new it after receiving value? I hate this solution.
>
> Chris
Sounds like "No, you cannot do it" but Chad J McQuinn said:
> The "hello(val)" will call whatever constructor of MySubClass is capable
> of taking an integer; here there is none. Add one and your example
> should be fine.
>
> MySobClass(int myVal) : MyClass(...whatever...) , val(myVal)
> {
> Func();
> }
>
> If, as you say in your comment, Func needs to use val, then you should
> remove the call to Func from the default constructor entirely. Or, if
> you never want MySubClass constructed without passing an int to the
> constructor, eliminate the default constructor entirely. If doing so
> gives you an error, then that means you are creating a MySubClass
> somewhere and not passing in an int.
- Next message: Chad J McQuinn: "Re: Default constructors, passing argument"
- Previous message: Peter: "Re: Default constructors, passing argument"
- In reply to: Chris Newton: "Re: Default constructors, passing argument"
- Next in thread: jeffc: "Re: Default constructors, passing argument"
- Reply: jeffc: "Re: Default constructors, passing argument"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|