user3523222
user3523222

Reputation: 33

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;
};

Upvotes: 0

Views: 510

Answers (3)

juanchopanza
juanchopanza

Reputation: 227370

It isn't clear where you want to access the base class' method, but you can do this:

_map->Map::populateMap(); // calls base class member function
_map->populateMap();      // calls derived class member function

Upvotes: 2

jsantander
jsantander

Reputation: 5102

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.

Upvotes: 1

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

Have your Colormap constructor pass the arguments to the base constructor. Once virtual delared in base class, derived classes don't need to declare virtual again.

Upvotes: 0

Related Questions