2

When reviewing old code I encountered the following construction:

class Base
{
    public:
    Base(Child* aChild = 0){}
}

class Child: public Base
{
    public:
    Child():Base(this){}
}

Beside the fact that it looks awful, I wonder if it is safe to provide the 'this' pointer to the parent class in the initializer list? I found a few examples where the 'this' pointer from the parent is provided to a child class pointer member for example in this question by bavaza. Since the parent class is kind of an implicit member of the child class, I suppose that the above construction is safe, as long as the Base class is not using the this pointer inside its constructor. Nevertheless, I want to confirm that this is always the case and not undefined behavior.

I'm surprised that I did not find an answer to this basic question. Probably I used the wrong key words. So please excuse me if it turns out to be a duplicate nevertheless.

Community
  • 1
  • 1
Paul R.
  • 678
  • 5
  • 19
  • 2
    Yes this is fine. Yes the SO search feature is a pain – M.M Dec 13 '16 at 10:08
  • 2
    Your concrete example is fine. But be careful. As I recall the standard's phrasing is "can be used, but only in limited ways". Because at the time `Base` receives that pointer, the `Child` part isn't yet constructed. Also, some compilers, like Visual C++, tend to issue warnings about this. – Cheers and hth. - Alf Dec 13 '16 at 10:11
  • @Cheersandhth.-Alf :Can you please specify in 'what limited ways'? – sameerkn Dec 13 '16 at 12:18
  • 1
    @sameerkn: C++11 §3.8/5 (with the “limited ways” phrasing) refer you to §12.7 for the case of an object under construction. §12.7/1 tells you that “For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior”. And there is wording about conversion to base class pointer or reference (UB if construction of derived class hasn't started). And there's more, but in summary: just don't dereference that pointer until the derived class constructor body has started executing. – Cheers and hth. - Alf Dec 13 '16 at 12:41
  • @Cheersandhth.-Alf: thanks. That means pointer `aChild` is of no use inside Base class c'tor apart from just knowing the address of memory location of derived class Child's object. – sameerkn Dec 13 '16 at 12:47
  • @Cheersandhth.-Alf Thank you for your explanation. I was really scared that this code could blow up in my face when porting to a different compiler. – Paul R. Dec 13 '16 at 14:20

0 Answers0