Reputation: 3993
in my object State, i'd like to have object pq. but pq needs to be initialized with a parameter. is there a way to include a class that depends on a parameter into another class?
file.h
class Pq { int a; Pq(ClassB b); }; class State { ClassB b2; Pq pq(b2); State(ClassB b3); };
file.cc
State::State(ClassB b3) : b2(b3) {}
Upvotes: 0
Views: 126
Reputation: 6901
Class State{
public:
State(ClassB& bref):b2(bref),pq(b2){} // Depends on the order you declare objects
// in private/public/protected
private:
ClassB b2;
Pq pq;
};
In the above code you have to maintain that order in the initialization list otherwise you will get what not expected..therefore quite risky
Upvotes: 1
Reputation: 11245
You can initialize it in the initializer list, just like you do with b2
:
State::State(ClassB b3) : b2(b3), pq(b2) {}
Keep in mind that members are initialized in the order they are declared in the header file, not the order of the initializers in the initializer list.
You need to remove the attempt at initialize it in the header as well:
class Pq
{
int a;
Pq(ClassB b);
};
class State
{
ClassB b2;
Pq pq;
State(ClassB b3);
};
Upvotes: 2