Reputation: 896
I have two classes, Foo
and Bar
. Bar
contains an instance of Foo
, which needs to be initialized whit some data in a file. An initializer list should not be ok, because at the time of the initialization the computer doesn't already know what value assign to Foo
.
class Foo {
int x;
public:
Foo(int new_x) : x(new_x) {}
};
class Bar {
Foo FooInstance;
public:
Bar(const char * fileneme)
/* Auto calls FooInstance() constructor, which does not exist
Shoild I declare it to only avoid this error? */
{
/* [...] reading some data from the file */
// Init a new FooInstance calling FooInstance(int)
FooInstance = Foo(arg);
/* Continue reading the file [...] */
}
};
It would be a good choice to create a new object, initializing it, then copying it in FooInstance
as shown in the source?
Or maybe declaring FooInstance
as raw pointer, then init it with new? (and destroy it in Bar
destructor)
What is the most elegant way to initialize FooInstance
?
Upvotes: 1
Views: 162
Reputation: 217275
You may use delegating constructors (since C++11) and extra function:
MyDataFromFile ReadFile(const char* filename);
class Bar {
Foo FooInstance;
public:
Bar(const char* fileneme) : Bar(ReadFile(filename)) {}
private:
Bar(const MyDataFromFile& data) : FooInstance(data.ForFoo)
{
// other stuff with MyDataFromFile.
}
};
Upvotes: 5
Reputation: 477040
If the necessary argument can be computed, then you can use a helper function:
class Bar
{
static int ComputeFooArg() { /* ... */ };
public:
Bar(const char * filename) : FooInstance(ComputeFooArg())
{
// ...
}
// ...
};
Upvotes: 4