Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

c++ - Access derive class from a base class pointer

I want to access derive class from a base class pointer, but my code is not working and I am not getting what is wrong

#include <iostream>
using namespace std;

class base
{

public:
    int n1;
    void display()
    {
        cout << "
Base number is: " << n1 << endl;
    }
};
class derive : public base
{
public:
    int n2;
    void display()
    {
        cout << "
Base number is: " << n1 << endl;
        cout << "
Derived number is: " << n2 << endl;
    }
};

int main()
{
    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->n2 = 66; //access derive class via base pointer //here it is showing that 'base class has no member n2'
    bptr->display();
}

question from:https://stackoverflow.com/questions/65881377/access-derive-class-from-a-base-class-pointer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...