Pergunta

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>??

Foi útil?

Solução 2

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.

Outras dicas

WTF?

// Example translation unit
#include <vector>

using namespace std;

class A {
    class X {
        int x;
    };

    getX() {
         return x_;
    }

    X x_;
    vector<X> x_vector_;
}

class B : public A {
    class x {
         int x;
         int y;
    };

    X x_;
}

Example compile errors:

> g++ -Wall -pedantic tmp.cpp
tmp.cpp:10:10: error: ISO C++ forbids declaration of 'getX' with no type [-fpermissive]
tmp.cpp:16:1: error: expected ';' after class definition
tmp.cpp: In member function 'int A::getX()':
tmp.cpp:11:17: error: cannot convert 'A::X' to 'int' in return
tmp.cpp: At global scope:
tmp.cpp:6:11: error: 'class A::X' is private
tmp.cpp:24:5: error: within this context
tmp.cpp:25:1: error: expected ';' after class definition

In particular: error: 'class A::X' is private.

Q: How exactly do you propose for the subclass to access any private ("hidden") members or member functions in the superclass?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top