In C++, I have an object A that has a constructor that accepts an istream (to load itself from a file). I have another class that has an A as a member. I can’t call A‘s constructor from the initialization list because I didn’t open the istream yet. Once I open it in the constructor of my class, it is too late to call the constructor of A. Is there some way to open an istream in the initialization list into some temporary object so that I can send it to A‘s constructor?
And if there is, is there any type of guarantee on the order the initialization list is called so that the istream would get initialized before the A?
An example may help:
class A {
public:
A(std::istream const&);
}
class B {
public:
B(std::istream const&);
}
class MyClass {
A a;
B b;
public:
MyClass() : a(is), b(is) { // <-- How to do this?
std::istream is("path");
}
}
Here’s yet another idea… If you want to avoid dynamic allocations and use a single, temporary
istream, you can move the load phase ofAandBaway from their constructor:This, BTW, calls for
AandBinheriting the load abilities from some shared parent, but that’s obviously beyond the scope of this question.