Search code examples
c++functioninheritanceconstructorvirtual

Using overriden function in base class constructor for derived class


I'm very new to C++ programming so I wanted to write some simple code to get used to the syntax. I have deliberately ignored pointers and references for the moment.

During coding, I was practising inheritance and I wanted to create a class Hand which represents a hand of cards. The base class has a function called update(), which is used to initialize the "total" and "notation" properties upon construction. Moreover it is possible to add cards to the hand using the add() function which adds a card to the hand and triggers update() to update the properties appropriately.

#include<vector>

class Hand
{
public:
    std::vector<int> cards;
    int total;
    std::string notation; // Abbreviated notation of the object
    // Constructor
    Hand(std::vector<int> cards);
    void update();
    void add(int card);
}

Hand::Hand(std::vector<int> cards)
{
    this->cards = cards;
    update();
}

void Hand::update()
{
    total = 0;
    notation += "{ ";
    for (int card: cards)
    {
        total += card;
        notation += std::to_string(card) + " ";
    }
    notation += "}";
}

void Hand::add(int card)
{
    cards.push_back(card);
    update();
}

Next, I wanted to create a more specific class of Hand called StandHand, which does all the same things as Hand but it also has a variable that changes when the total reaches a particular value.

Initially I thought I could just write the subclass as shown below, but alas.

class StandHand : public Hand
{
public:
    int stand;
    StandHand(std::vector<int> cards, int stand);
    void update();
}

StandHand::StandHand(std::vector<int> cards, int stand) : Hand(cards)
{
    this->stand = stand;
    updateHand();
}

void StandHand::update()
{
    Hand::update();
    notation += stand <= total ? " (stand)" : "";
}

But when I invoke the add() method on a StandHand object, it does not use the StandHand::update() method, rather it uses the base update() method. How can I make sure that the add() method, when used in a subclass of Hand, uses the update() function of that subclass?


Solution

  • For starters in the code there is no overloaded functions. The declaration of update in the derived class hides the declaration of the function with the same name in the base class.

    As the member function add is declared in the base class then the name of the function update also is searched in the base class.

    Declare the function update as a virtual function.

    class Hand
    {
    public:
        // ...
        virtual void update();
    };
    
    class StandHand : public Hand
    {
    public:
        // ///
        void update() override;
    };