Traditionally, in C++, you would create any dependencies in the constructor and delete them in the destructor.
class A
{
public:
A() { m_b = new B(); }
~A() { delete m_b; }
private:
B* m_b;
};
This technique/pattern of resource acquisition, does it have a common name?
I'm quite sure I've read it somewhere but can't find it now.
Edit:
As many has pointed out, this class is incomplete and should really implement a copy constructor and assignment operator.
Originally, I intentionally left it out since it wasn't relevant to the actual question: the name of the pattern. However, for completeness and to encourage good practices, the accepted answer is what it is.
class A{ B m_b = {}; }
and you get pretty much the same but without risky pointers and using less than 1/4th the code. – Tellurateprivate:
because the entire point of theclass
keyword is to define members private as default, as they're meant to be on top of the class, and not hidden at the bottom in a place you need to scroll down the entire page to see them. In my 30 years of programming I have never seen a single argument to put the members at the bottom and the language is clearly meant to have them at the top. – Tellurate