Mark
Mark

Reputation: 611

In-class / constructor member initialization

I'll try to summarize what I need in both words and code snippets.

I have a class, Foo, which contains a data member of the type Bar:

class Foo {
  public:

    Bar instance_of_Bar;

    Foo (int some_data) 
    {
      // I need to initialize instance_of_Bar using one of its
      // constructors here, but I need to do some processing first


      // This is highly discouraged (and I prefer not to use smart pointers here)
      instance_of_bar = Bar(..);
      // As an unrelated question: will instance_of_Bar be default-initialized 
      // inside the constructor before the above assignment?
    }
}

Obviously, the "correct" way to do it would be to use an initializer list like this:

Foo (int some_data) : instance_of_Bar(some_data) {}

But this is not an option because I need to do some work on some_data before passing it to the Bar constructor.

Hopefully I made myself clear. What would be the RAII way of doing it with minimal overhead and copying (The Bar class is a hefty one).

Thanks a bunch.

Upvotes: 1

Views: 73

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

"But this is not an option because I need to do some work on some_data before passing it to the Bar constructor."

What about providing another function to "do some work on some_data":

 Foo (int some_data) : instance_of_Bar(baz(some_data)) {}

 int baz(int some_data) {
     // do some work
     return some_data;
 }

Upvotes: 4

Related Questions