Is using a reference to a derived class member in its base class well defined in C++?

  c++, oop, undefined-behavior

I was looking into some code and it seemed to work but I am not sure if it is defined behaviour.

I think there is a problem in it because Base is constructed with a reference to a Derived member variable – wich is in my understanding constructed after Base.

I did some research on this and all I found were answers stating that Base is constructed before Derived, and Arguments from a Derived Constructor can be forwareded to the Base constructor.

But what about Derived Members, can they safely be forwareded to a Base Constructor?
Might Constructor and Destructor or even Member-Functions in Base work with invalid objects?

Here is simple code sample with the problem:

class Base
{
public:
   Base(SomeClass & obj): m_obj(obj)
   {
       // Does using m_obj here cause problems with a Derived instance?
   }

   virtual ~Base()
   {
       // Does using m_obj here cause problems with a Derived instance?
   }
   
   void SomeMethod()
   {
       // Does using m_obj here cause problems with a Derived instance?
   }
   
private:
   SomeClass & m_obj;
};


class Derived : public Base
{
public:
    Derived():Base(m_derObj){}

private:
    SomeClass m_derObj{123};
};

OnlineGDB

Maybe I am missing some gurantee C++ gives – or maybe we were just lucky and the error never occured.

Source: Windows Questions C++

LEAVE A COMMENT