vendredi 12 novembre 2021

Accessing fields of child class via shared_ptr

Is it possible to access fields in the instance of child class via shared_ptr? For instance, the code below does not compile. However, if I just declare a variable like Bar bar(2), then I can access field b in a usual way, e.g. bar._b.

#include <memory>
#include <iostream>

using namespace std;

struct Foo {};

class Bar : public Foo {
public:
    Bar(int b) : _b(b) {};
    const int _b;
};

int main() {
    shared_ptr<Foo> bbar = make_shared<Bar>(3);
    cout << bbar->_b;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire