Search code examples
c++functionpolymorphismvirtual

C++ Access a Base Class's virtual function through a derived object


I'm attempting to create a text-based RPG for my Adv. Programming course and I'm a bit unsure about the polymorphism. I'm building this in pieces and currently I'm trying to get a visual display going based on a prior assignment that involved drawing colored characters to the console via coordinates to create a map. So I have this main:

#include "Map.h"


using namespace std;

int main()
{
    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);

    ColorMap* _map = new ColorMap(handle, "north");

}

and I want to point to the base class's function populateMap, and then access the derived class's populateMap. Here is the header for reference

#pragma once

#include <Windows.h>
#include <string>

using namespace std;

class Map
{
public:
    Map(HANDLE handle, string direction);
    ~Map(){};

    virtual void update();
    virtual void populateMap();

    void drawPoint(int x, int y) const;

protected:
    HANDLE mHandle;
    char mMap[15][15];
    char mWall;
    char mSpace;
    string mIncomingDirection;
};

class ColorMap : public Map
{
public:
    ColorMap(HANDLE handle, string direction);
    ~ColorMap(){};

    virtual void update();
    virtual void populateMap(); 

    void drawMap();

private:
    int mColor;
};

Solution

  • if you need ColorMap implementation to extend the base implementation: Your ColorMap's populateMap() implementation should go:

    void ColorMap::populateMap() {
        Map::populateMap(); // first call the base class
        // now do your things...
    }
    

    If you have

    Map *m=new ColorMap(...);
    
    m->populateMap();
    

    That will call the derived class method.... However from within that method you can still access the parent class version of the method and run it (before, after or in-between) the rest of the code.