This works just fine for me:
bar(int y, int z) : foo(y)
{
_foo_ptr_1 = new foo(y);
_foo_ptr_2 = new foo(z);
}
Please not that trying to invoke a class constructor directly like it was a static method is not how classes are constructed in C++. At the very least, you use new classname(arguments)
, as above.
This is not really recommended however... explicit memory management using new
and delete
is easy to get wrong.
First, consider that you may not have to allocate any foo
instances at all.. you can just have simple member variables:
class bar : public foo {
public:
bar(int y, int z) : foo(y), _foo_1(y), _foo_2(z)
{
}
private:
foo _foo_1;
foo _foo_2;
};
If you really must construct new instances the hard way, you should consider using smart pointers such as unique_ptr
.
class bar : public foo {
public:
bar(int y, int z) : foo(y), _foo_ptr_1(new foo(y)), _foo_ptr_2(new foo(z))
{
}
private:
std::unique_ptr<foo> _foo_ptr_1;
std::unique_ptr<foo> _foo_ptr_2;
};
unique_ptr
ensures that your resources are correctly deallocated when their owner is destroyed. If your _foo
member variables don't belong exclusively to their parent bar
instance, then you can use shared_ptr
instead. It is well worth reading up on the use of these utility classes.