title: Overriding a member variable in C++
body: <p>I have run into a bit of a tricky problem in some C++ code, which is most easily described using code. I have classes that are something like:</p>
  
  <pre><code>class MyVarBase
  {
  }
  
  class MyVar : public MyVarBase
  {
      int Foo();
  }
  
  class MyBase
  {
  public: 
      MyBase(MyVarBase* v) : m_var(v) {}
      virtual MyVarBase* GetVar() { return m_var; }
  private:
      MyVarBase* m_var;
  }
  </code></pre>
  
  <p>I also have a subclass of MyBase that needs to have a member of type MyVar because it needs to call Foo. Moving the Foo function into MyVarBase is not an option. Does it make sense to do this:</p>
  
  <pre><code>class MyClass : public MyBase
  {
  public:
      MyClass(MyVar* v) : MyBase(v), m_var(v) {}
      MyVar* GetVar() { return m_var; }
  private:
      MyVar* m_var;
  }
  </code></pre>
  
  <p>This seems to work but looks really bad and I'm not sure if it's going to cause a memory leak or break a copy constructor. My other options might be to name the MyVar variable in MyClass something else but have it be equal to the m_var pointer in the base, or to templatise MyBase on the MyVar type. </p>
  
  <p>All these options don't seem ideal so I wanted to know if anyone else has run into a situation like this and if there is a good way to make it work.</p>