Getter-function for derived class in derived class, when using pointer to base class

旧街凉风 提交于 2021-02-11 18:21:44

问题


I have two abstract base classes, class_data and BaseClass, with derived classes overridden_class_data : public class_data and DerivedClass : public BaseClass:

class class_data{
public:
    int val_a = 0;
    double val_b = 0.;
};

class overridden_class_data : public class_data{
public:
    int val_c = 0.;
};    

class BaseClass{
public:
    BaseClass(){};

    virtual void print_data() = 0;
    virtual class_data *get_local_data() = 0;

    class_data local_class_data;
};

class DerivedClass : public BaseClass{
public:
    DerivedClass(){
        local_class_data.val_a = 10;
        local_class_data.val_b = 100.;
        local_class_data.val_c = 14;
    };

    void print_data() override{
        std::cout << "Hello World\n";
    }

    class_data * get_local_data() override {
        return &local_class_data;
    }

    overridden_class_data local_class_data;
};

Now, in external functions, I would like to use the base class pointer, while still transferring the derived class to the function (such that I can use the same function for several derived classes). In order to access the class variable local_class_data, I need a getter-function, else the class variable of the base class will be accessed. Here I wanted to use the same approach, i.e. use a pointer of the base class, while returning the derived class. Unfortunately, that does not work, and the line

std::cout << class_pointer->get_local_data()->val_c << '\n';

results in a compilation error

main.cc: In function ‘void test_func(BaseClass*)’:
main.cc:52:51: error: ‘class class_data’ has no member named ‘val_c’; did you mean ‘val_a’?
   52 |     std::cout << class_pointer->get_local_data()->val_c << '\n';

after the compiler still assumes that I am pointing to the class BaseClass (containing class_data) and not to the class DerivedClass containing overridden_class_data.
Is there a way I could solve my problem, while retaining the advantages of having an abstract base class?

来源:https://stackoverflow.com/questions/59919913/getter-function-for-derived-class-in-derived-class-when-using-pointer-to-base-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!