Search code examples
c++vectorsmart-pointersderived-class

C++ access member of templated derived class without typecast


Is it possible to acces a member of a derived class using a pointer to the base class?

// Example program
#include <iostream>
#include <vector>
#include <memory>
#include <string>

class A {
    public:
    std::string x = "this is the wrong x\n";
    };

template <class T>
class B : public A {
    public:
    T x;
    };

int main()
{
    std::vector<std::unique_ptr<A>> vector;
    auto i = std::make_unique<B<int>>();
    i->x = 6;
    vector.push_back(std::move(i));
    for(auto &element : vector){
        std::cout << element->x;
    }
}

Here I'm always getting the output from class A. I cannot typecast it because I don't know whether the element is of type A or type B in advance. Is there a proper way to do this?


Solution

  • The proper way would be to make a virtual function to perform the task like printing.

    class A {
    public:
        std::string x = "this is the wrong x\n";
        virtual ~A() = default;
        virtual void print() const { std::cout << x; }
    };
    
    template <class T>
    class B : public A {
    public:
        T x;
        virtual void print() const override { std::cout << x; }
    };
    
    int main()
    {
        std::vector<std::unique_ptr<A>> vector;
        auto i = std::make_unique<B<int>>();
        i->x = 6;
        vector.push_back(std::move(i));
        for(auto &element : vector){
            element->print();
        }
    }