Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overriding protected field members in C++ not working?

In the following, I expected class Child‘s protected field member _AorB to be of type B, and not A, but reality shows otherwise.

What am I mis-understanding, and how can I adjust the code for the desired behavior?

class A{
    public:
       void doit(){
           std::cout<<" this is A!"<<std::endl;
       }
    
};

class B{
    public:
       void doit(){
           std::cout<<" this is B!"<<std::endl;
       }
    
};

class Parent{
    public:
      void doit(){
          _AorB.doit();
      }
      protected:
        A _AorB;
};

class Child: public virtual Parent{
    protected:
      B _AorB;
};

int main()
{
    cout<<"Hello World";
    auto c = Child();
    c.doit(); // I expected this to print "This is B" because c is Child(), and Child class's _AorB is of type B.
    return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can make such changes:

template <typename AorB>
class Parent{
    public:
      void doit(){
          _AorB.doit();
      }
      protected:
        AorB _AorB;
};

class Child: public virtual Parent<B> {
}

Also take a look at What are the rules about using an underscore in a C++ identifier?

  • Reserved in any scope, including for use as implementation macros:
    • identifiers beginning with an underscore followed immediately by an uppercase letter
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading