Вы можете использовать объединение для этого (требуется C ++ 11):
#include <new>
class Foo {
public:
Foo(int a) { }
};
class Bar {
public:
Bar() {
new(&m_foo) Foo(42); // call the constructor
// you can use m_foo from this point
}
~Bar() {
m_foo.~Foo(); // call the destructor
}
private:
union { // anonymous union
Foo m_foo;
};
};
Обратите внимание, что вам нужно явно вызвать деструктор m_foo
в ~Bar()
.