new operator and class-type instance members

Hi,

I have a simple question about using the new operator on classes with instance members of other class types. If I have a class foo with the following definition:

1
2
3
4
5
class Foo {
	public:
		Foo1 foo1;
		Foo2 foo2;
	};


and I write the following in my main():

 
static Foo* foo = new Foo;


...does that allocate memory for the instance members foo1 and foo2 as well? I know that instantiating a Foo type calls the constructors for its instance members (Foo1 and Foo2), but is writing the above allocation the same as:

1
2
3
4
5
Foo1* _foo1 = new Foo1;
Foo2* _foo2 = new Foo2;

(foo->foo1) = (*_foo1);
(foo->foo2) = (*_foo2);


If not, how do I allocate memory for the instance members? Likewise, does explicitly calling the destructor for Foo, also deallocate memory of its instance members foo1 and foo2?

Thanks,

Andrew
Your first example is right; your second is a memory leak.

And yes, Foo's destructor will implicitly run the destructor for all of the data members of Foo.

There is very rarely ever a need for you to call a destructor explicitly.
Topic archived. No new replies allowed.