I want to initialize a class member which is also another class object.The problem is that, I have to initialize the member with variables that I figure out after doing some operations on my constructor. Let me show the sample code.
class Child_class
{
private:
int var1, var2, var3;
public:
DateTime(int var1 = 1970, int var2 = 1, int var3 = 1);
};
second class:
class Owner_class
{
private:
Child_class foo;
public:
// I have to make some string split operations on string_var variable
// and get some new variables.After that, I need to initialize child_class with new variables
Owner_class( string string_var, int test);
}
One way to do that, I know I could write :
Owner_class::Owner_class():
Child_class(new_var1,new_var2,new_var3) {
// but since I'll find new_var1,new_var2 and new_var3 here.I couldnt use this method.
// Am I right ?
}
Is there anyone to help me ? thanks in advance!
You can write a function to do the calculations for you and return a Child_class
object, and use this to initialize your instance in the Owner_class
constructor initialization list:
Child_class make_child_object(string string_var, int test)
{
// do stuff, instantiate Child_class object, return it
}
Then
Owner_class(string s, int n) : foo(make_child_object(s, n) {}
If this method is unsuitable, then an alternative is to give Child_class
a default constructor, and assign it a value in the Owner_class
constructor body:
Owner_class(string s, int n)
{
// foo has been default constructed by the time you gethere.
// Do your stuff to calculate arguments of Child_class constructor.
....
// construct a Child_class instance and assign it to foo
foo = Child_class(a, b, c);
}