Search code examples
c++inheritanceconstructor

How to override member of base class after inheritance in C++


i have this :

class A {
    public :
        A(int i ) : m_S(i)
        {  
            m_Pa = new Foo(*this) ;
        }
    private :
        int m_S ;
        Foo* m_Pa;
}

and derived class 

class B : public A {
    public :
        B() : A (242) 
        {
          // here i like to override the A class m_Pa member but i don't know how to do it right 
        }
}

Solution

  • your m_Pa should be protected than you can call like:

     B() : A (242), m_Pa(12) 
     {
    
     }
    

    or

     B() : A (242)
     {
       m_PA = 55
     }
    

    or you should make a public or protected function which changes m_Pa

     class A {
         public :
             A(int i ) : m_S(i)
             {  
                  m_Pa = new Foo(*this) ;
             }
    
            void setPA(int val)
            {
                 m_PA = val;
            }