Search code examples
c++inheritancegcccompiler-errorsclass-members

Inherited class member with the same name as child constructor


Consider this example:

    class Label{
    public:
        std::string Text;    
    };

    class Text:
        public Label
    {
    public:
        Text(std::string text) {}
    };

    int main()
    {
        Text text("");
        text.Text; //<---- GCC CE: Invalid use of 'class Text'
        return 0;
    }
    class Text:
        public Label
    {
    public:
        Text(std::string text) {}
        using Label::Text; // doesn't help either
    };

How could one access inherited class member if it has the same name as child class?

    class Text:
        public Label
    {
    public:
        Text(std::string text):
            Text::Text(Label::Text){}
        std::string &Text;
    };

Could something like this work? (I know that code above does not.)


Solution

  • Here's a workaroud (which is quit confusing); you can access data member of base class via the base class name. e.g.

    text.Label::Text;