You cannot access derived class' members using a base pointer, if you are sure that bptr
is indeed pointing to a derive
instance, you could cast it to a pointer to derive
and use it
auto dptr = static_cast<derive*>(bptr);
dptr->n2 = 66;
EDIT: There is a bigger problem in your code, display
is not virtual in base class, hence the class derive
is not actually polymorphic.
static_cast
will complain at compile time itself, if it sees that there is no conversion from base*
to derived*
It won't prevent though from doing something as below
base b;
base *bptr; //base pointer
bptr = &b;
bptr->n1 = 44; //access base class via base pointer
bptr->display();
derive d;
cout << "
";
//bptr = &d; //bptr is still pointing to a base instance.
auto dptr = static_cast<derive*>(bptr);
dptr->n2 = 66;
A better way is to use dynamic_cast
and test if the conversion was actually successful
auto dptr = dynamic_cast<derive>(bptr);
if (dptr)
dptr->n2 - 66; // indeed bptr holds a derive instance
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…