Others have posted solutions using raw pointers, but a smart pointer would be a better idea:
class MyClass { std::unique_ptr<Object> pObj; // use boost::scoped_ptr for older compilers; std::unique_ptr is a C++0x feature public: MyClass() { // ... pObj.reset(new Object(...)); pObj->foo(); } // Don't need a destructor };
This avoids the need to add a destructor, and implicitly forbids copying (unless you write your own operator= and MyClass(const MyClass &).
If you want to avoid a separate heap allocation, this can be done with boost's aligned_storage and placement new. Untested:
template<typename T> class DelayedAlloc : boost::noncopyable { boost::aligned_storage<sizeof(T)> storage; bool valid; public: T &get() { assert(valid); return *(T *)storage.address(); } const T &get() const { assert(valid); return *(const T *)storage.address(); } DelayedAlloc() { valid = false; } // Note: Variadic templates require C++0x support template<typename Args...> void construct(Args&&... args) { assert(!valid); new(storage.address()) T(std::forward<Args>(args)...); valid = true; } void destruct() { assert(valid); valid = false; get().~T(); } ~DelayedAlloc() { if (valid) destruct(); } }; class MyClass { DelayedAlloc<Object> obj; public: MyClass() { // ... obj.construct(...); obj.get().foo(); } }
Or, if Object is copyable (or movable), you can use boost::optional:
class MyClass { boost::optional<Object> obj; public: MyClass() { // ... obj = Object(...); obj->foo(); } };
Object* myObj;