Search code examples
c++base-classpure-virtual

How to perform specific tasks for each subclass in the base class constructor


I have a base class. For example:

class CData{
public:
    CData(const std::string &_filename)
    {
        m_filename = _filename;
        // LodaData(); // wrong
    }

    virtual void LoadData() = 0;
private:
    std::string m_filename;
};

And, a subclass:

class COtherData: public CData{
public:
    COtherData(const std::string &_filename): CData(_filename) {}

    virtual void LoadData() {
    // some code to load data
    ...
    }
};

I want to know how to perform some tasks in base class for subclasses.


Solution

  • The problem is that you call virtual function from constructor - you should avoid it. Instead you need to add a function to the base class that will call your virtual functions, which eventually end up with calling overridden function of the child class. Thus I will change your base class in the following way:

    class CData
    {
    public:
        CData(const std::string &_filename)
            : m_filename(_filename)
        {}
    
        void performTask()
        {
            LoadData();
            // ... do something else
        }
    
        virtual void LoadData() = 0;
    private:
        std::string m_filename;
    };