Search code examples
c++classconstructorderived-classbase-class

Including base class variables in the initializer list in the derived class


My project is to create a dive logbook. There is the DiveInfo base class and Equipment derived class. The equipment may change from dive to dive, so obviously it needs to get the variables for specific dives, according to the given data by the user.

This is the Equipment.h:

#pragma once
#include "DiveInfo.h"
#include <string>

class Equipment : public DiveInfo
//manage and capture information about the diving equip
{
private:    
    std::string equipmentCondition;
    std::string equipmentType;
    std::string maskType;
    double tankSize;

public:
    Equipment(const std::string& diveSiteName, int depth, int duration, double waterTemperature, double visibility, const std::string& notes,
              const std::string& equipmentCondition, const std::string& equipmentType, const std::string& maskType, double tankSize);
    
    std::string getEquipmentType() const;
    std::string getEquipmentCondition() const;
    double getTankSizeI() const;
    double getSac() const;
};

I already have a constructor in the DiveInfo for those variables (from diveSiteNames 'til notes). The question is, do I have to include the DiveInfo's variables in the initializer list for the Equipment.h's constructor? It may be a bold question as well, but couldn't this be done with some virtual function or with some template? Or would it overcomplicate things completely?


Solution

  • Each class should initialize itself and only itself. It should let parent classes do their own initialization.

    You do this by, first thing in your constructor initializer list, "call" the base class constructor.

    As a simple example:

    struct base
    {
        int value;
    
        base(int val)
            : value{ val }
        {
        }
    };
    
    struct derived : base
    {
        std::string string;
    
        derived(int val, std::string const& str)
            : base{ val }, string{ str }
        {
        }
    };
    

    The derived constructor initializer list first invokes the base class constructor to do its initialization, followed by the derived member initialization.