Re: deferring member object instantiation to constructor
v4vijayakumar wrote:
Is there any way to defer instantiation of " t1" to the constructor of
"test1"? because, "t1" can only meaningfully initialized in the "test1"
constructor.
#cat test.cpp
#include <iostream>
using namespace std;
class test
{
public:
test()
{
cout << "hello" << endl;
}
};
class test1
{
test t;
public:
test1()
{
cout << "hello1" << endl;
}
};
int main(int argc, char *argv[])
{
test1 t1;
return 0;
}
#g++ test.cpp
#./a.out
hello
hello1
Since your question as stated doesn't make sense, I think you meant to
ask: Can I defer the calling of the constructor test::test() for the
member object t within test1's constructor? The answer is no and yes --
no, because the member object will be default constructed in the
(implicit) initializer list before the body of the constructor
executes, and yes, because you could change the object to a (smart)
pointer so that construction of t is delayed until you are ready to do
it. For instance:
class test1
{
public:
test1()
{
cout << "hello1" << endl;
// Do some other stuff to get ready for making a test object
t.reset( new test );
}
private:
std::auto_ptr<test> t;
// Disable functions because of auto_ptr's
// destructive copy semantics
test1( const test1& );
test1& operator=( const test1& );
};
Of course, using std::tr1::scoped_ptr (aka boost::scoped_ptr) would be
preferable since it would minimize mistakes with copying auto_ptrs.
Keeping the rest of the program the same but substituting my test1
class would give this output:
hello1
hello
Cheers! --M