Reputation: 315
I have the classes SmallClass
and BigClass
. BigClass
as a private attribute that is an object of SmallClass
. I've read about initializer lists, but the problem is that I cannot predict the value I need to pass to the constructor of SmallClass
. The code looks something like this:
class SmallClass {
public:
SmallClass(int);
private:
int boo;
}
SmallClass::SmallClass(int i) {
boo = i;
}
class BigClass {
public:
BigClass();
private:
SmallClass sc; // I guess this calls the constructor (and does not compile)
};
BigClass::BigClass() {
int foo;
/* Do stuff. I end up with a "foo" having a non predictable value. */
sc = SmallClass(foo); /* Is there a way to do something like this? */
}
Upvotes: 3
Views: 1263
Reputation: 238301
Is there an alternative to initializer lists?
Yes. Default member initializer is an alternative for initializer list. However, that is not useful for your case. In fact, it is only useful when the arguments of the constructor are predictable.
"Non-predictability" of foo
is not a problem for the initializer lits; you don't need an alternative. Simply call a function:
int get_foo() {
int foo;
/* Do stuff. I end up with a "foo" having a non predictable value. */
return foo;
}
BigClass::BigClass() : sc(get_foo()) {}
If "do stuff" includes access to members (there are no other members in the example, I assume that it may be a simplification), then you can use a member function to achieve that. However, keep in mind that you may only access members that were initialized before sc
.
Upvotes: 2
Reputation: 26
I suggest a workaround:
class SmallClass
{
public:
SmallClass();
public:
void SetBoo(int value);
private:
int boo;
};
SmallClass::SmallClass()
{
boo = 0;
}
void SmallClass::SetBoo(int value)
{
boo = value;
}
class BigClass
{
public:
BigClass();
private:
SmallClass sc; // I guess this calls the constructor (and does not compile)
};
BigClass::BigClass()
{
int foo;
/* Do stuff. I end up with a "foo" having a non predictable value. */
sc.SetBoo(foo); /* Yes, you can set the boo member */
}
Upvotes: 1