Is something similar to this possible? This way it produces an error.
class A {
public:
virtual std::string key;
};
class B : public A {
public:
std::string key;
};
int main()
{
A a;
a.key = "Foo";
return 1;
}
No, because this doesn't really make sense. Remember that a subclass contains all members of its parent class; therefore, B
still has A
's std::string key
. Moreover, since B
's std::string key
is the same type, it's absolutely identical to A
's - so what was the point of overriding it?
Also, note that during construction, when we're running A
's constructor, B
's virtual methods won't be called. This means that if we access key
during A
's construction, we'd get A
's key - but then when B
is constructed, that key
would be shadowed, its data completely inaccessible.
That said, if you really do want to do something like this, for some reason, you'll need to use a virtual accessor function:
class A {
private:
std::string m_key;
public:
virtual std::string &key() { return m_key; }
virtual const std::string &key() const { return m_key; }
};
class B : public A {
private:
std::string m_key;
public:
virtual std::string &key() { return m_key; }
virtual const std::string &key() const { return m_key; }
};
int main()
{
B b;
b.key() = "Foo";
return 0;
}