Let's say I have two classes, Parent
and Child
. Any instances of the Child
class must occur as members of a Parent
class, and the Child
class has, as a data member, a pointer to that Parent
. Thus, the Child
class has a single constructor that takes said pointer as its sole argument (and there is, by design, no default constructor).
At its simplest, then, we have code like the following (I have included the DoSomething
functions so that compilers won't optimize-away the pParent
member, which is otherwise unused in this MCVE):
class Parent; // Declaration to enable use of pointer in Child
void DoSomething(Parent* p, int x);
class Child {
private:
Parent* pParent;
public:
Child(Parent* pp) : pParent{pp} {}
// Would like a 'default'-style constructor, like below, where "nullptr" is replaced with a pointer-to-container
// Child(Parent* pp = nullptr) : pParent{ pp } {}
public:
void DoSomething(int x) { ::DoSomething(pParent, x); }
};
class Parent {
public:
Parent() {}
public:
Child Child1{ this };
// Child Child2; // error: 'Child': no appropriate default constructor available
};
As I have used in the above code, I can declare/instantiate Child
members using the { this }
initializer syntax; however, I typically have several thousand such instances in my projects (and there a number of different Child classes), and I was wondering if "Modern C++" (I generally use the C++17
standard) provides any way for the constructor to be declared in a manner similar in form to the commented-out version, but replacing the default argument value (nullptr
) with some kind of 'token' (or keyword) that will be converted to a pointer to the 'containing' Parent
class at compile-time, and thus hugely reducing the coding burden? Something like this:
Child(Parent* pp = id_of_containing_class) : pParent{ pp } {}
I am still in the process of getting fully 'up-to-speed' with the new language features since C++11
, and have not yet found such a tool. But there are many excellent coders here on SO who are far more familiar with what can and cannot be done!
(To provide some context for this: the Child
classes represent customized controls in customized dialog-boxes, derived from the Parent
class.)