class flow_rule_swift
{
private:
double a,b,n;
public:
flow_rule_swift(double x, double y, double z)
{
a = x;
b = y;
n = z;
}
}
class MaterialSwift
{
private:
double a,b,n;
flow_rule_swift FlowCurve(a,b,n);
public:
MaterialSwift(double x, double y, double z)
{
a = x;
b = y;
n = z;
FlowCurve.flow_rule_swift(a,b,n);
}
}
I have a class MaterialSwift and an object of class type flow_rule_swift within it. Now when I create an Object of type MaterialSwift, then I want a contructor to be invoked such that also the object of flow_rule_swift 'FlowCurve' gets initialized.
Something like this:-
class MaterialSwift obj_MaterialSwift(1.5,5.6,7.5);
Then the object 'FlowCurve' also is intialized using its contructor.
Is my above code ok?? Or does anybody have an idea?
(I understand the message might seem a bit cryptic)
This isn't really a nested class, but that's just semantics.
Anyway, you call member ctors via your ctor's initializer list. IE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class MaterialSwift
{
private:
double a,b,n;
flow_rule_swift FlowCurve; // no ctor call here
public:
MaterialSwift(double x, double y, double z)
: FlowCurve(x,y,z) // instead, put it here
{
a = x;
b = y;
n = z;
}
}; // don't forget your semicolons!
Note that you can initialize every member this way (even basic types like ints) as well as using specific ctors from your parent class:
1 2 3 4 5 6 7 8 9 10
class Child : public Parent
{
int myint;
public:
Child()
: Parent( 5, 6 ) // calls a specific Parent ctor
, myint(100) // and inits "myint" to 100
{ }
};
The catch is, the initializer list must list members in the same order they are declared in the class. (This isn't really a requirement, but some compilers will complain if you don't do it because of the order in which the members are initialized). This can be important if you need to use one member to initialize another:
1 2 3 4 5 6 7 8 9 10 11 12
class Foo
{
int first;
int second;
public:
Foo()
// : second(0), first(second) <--- BAD! 'first' is initialized before second
: first(0), second(first) // <--- okay!
{
}
};