c++member-hiding

Questions regarding hiding super class members


In my subclass I am hiding a super class member variable or type by redefining it in my sub class and wondering what happens to function calls that use the member variables hidden by the subclass. As an example:

class A {
    class X {
        int x;
    };

    X getX() {
         return x_;
    }
protected:
    X x_;
public:
    vector<X> x_vector_;
}

class B : public A {
    class x {
         int x;
         int y;
    };
protected:
    X x_;
}

What happens when I do the following:

B b;
b.getX();

Q1: Will this return A::x_ or B::x_ ??

How about:

B b;
b.x_vector_;

Q2: Will b.x_vector_ be of type vector<A::X> or vector<B::X>??


Solution

  • I tried the following compilable piece of code:

    #include <iostream>
    
    using namespace std;
    
    class A {
    public:
        class X {
        public:
            X () {
                i_ = 1;
            }
    
            int getI() {
                return i_;
            }
    
         protected:
            int i_;
         };
    
    int getX() {
        return xobject_.getI();
    }
    
    
    protected:
        X xobject_;
    };
    
    
    class B : public A {
    public:
        class X : public A::X {
        public:
            X() {
                i_ = 5;
            }
    
            int getI() {
                return i_;
            }
        protected:
            int i_;
        };
    
    
    protected:
        X xobject_;
    };
    
    
    int main (int argc, char** arv) {
        B b;
        std::cout << "value of b.getX(): " << b.getX() << std::endl;
        return 0;
    }
    

    Output:

    value of b.getX(): 1

    This answers both questions. If I don't redefine the function getX() and the vector x_vector in the subclass, the super class members will be used.