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;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, because this doesn’t really make sense. Remember that a subclass contains all members of its parent class; therefore,
Bstill hasA‘sstd::string key. Moreover, sinceB‘sstd::string keyis the same type, it’s absolutely identical toA‘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 accesskeyduringA‘s construction, we’d getA‘s key – but then whenBis constructed, thatkeywould 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: