'Object factory with derived classes containing different member methods than base class

So, I have some classes derived from a base class which should be created at runtime on some specific parameters for which I created a factory class

My base class is

class PostReceptionErrorModel : public ns3::Object {

    public:
        std::string getModel() { return m_model; }
        bool isEnabled() { return m_isEnabled; }
    protected:
        std::string m_model;
        bool m_isEnabled = false;

};

The derived class is

class PostReceptionRateErrorModel : public PostReceptionErrorModel {

    public:
        PostReceptionRateErrorModel(std::string model, std::string errorUnit, double errorRate, std::string ranVar);
        virtual ~PostReceptionRateErrorModel() {};
        std::string getErrorUnit() {return m_ErrorUnit;}
        double getErrorRate() {return m_ErrorRate;}
        std::string getRanVar() {return m_RanVar;}

    private:
        std::string m_ErrorUnit;
        double m_ErrorRate;
        std::string m_RanVar;
};

PostReceptionRateErrorModel::PostReceptionRateErrorModel(std::string model, std::string errorUnit, double errorRate, std::string ranVar) {
    m_model = model;
    m_ErrorUnit = errorUnit;
    m_ErrorRate = errorRate;
    m_RanVar = ranVar;
    m_isEnabled = true;
}

And the factory class is

class Factory
{
    public:
        static std::shared_ptr<PostReceptionErrorModel> CreateInstance(std::string name);
};

std::shared_ptr<PostReceptionErrorModel> Factory::CreateInstance(std::string name) {

    PostReceptionErrorModel * instance = nullptr;

    if(name == "ns3::RateErrorModel") {
        instance = new PostReceptionRateErrorModel("ns3::RateErrorModel", "Test", 0.1, "test");
    }

    if(instance != nullptr) {
        return std::shared_ptr<PostReceptionErrorModel>(instance);
    } else {
        return nullptr;
    }

}

In the main function I create an instance of PostReceptionRateErrorModel and call getErrorUnit

 auto RateErrorModel = Factory::CreateInstance("ns3::RateErrorModel");
    std::cout << RateErrorModel->getModel() << "\t" << RateErrorModel->getErrorUnit() << std::endl;

However, I get the following error message

error: ‘using element_type = class PostReceptionErrorModel’ {aka ‘class PostReceptionErrorModel’} has no member named ‘getErrorUnit’

As far as I can see, the shared pointer points to an instance of PostReceptionRateErrorModel. However, I don't understand why I can't call the method. What's the reason for this and is there a workaround?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source