2

i am having trouble with the following: i need to use enum to enumerate 4 inherited classes (at this point they have no difference between them other the the enum) and then return the type via a virtual function called "whoAmI", i don't understand the syntax as to how i would do the return part the following is the relevant code;

in class.h

virtual void whoAmI();
 enum gettype { easyTile, cropTile, waterTile, mediumTile};

in class.cpp

void tile::whoAmI()
{


}
Leo
  • 31
  • 1
  • 5

3 Answers3

2

You can change the return type of your function to the name of your enum, then use = 0 to declare the base class is pure virtual.

class ITile
{
public:
    enum class EType { easy, crop, water, medium };
    virtual EType whoAmI() const = 0;
};

Then the derived classes can override this method to return the correct enum type, for example

class EasyTile : public ITile
{
public:
    EasyTile() = default;
    EType whoAmI() const override { return EType::easy; }
};

class CropTile : public ITile
{
public:
    CropTile() = default;
    EType whoAmI() const override { return EType::crop; }
};

So as an example (live demo)

int main()
{
    std::vector<std::unique_ptr<ITile>> tiles;
    tiles.emplace_back(new EasyTile);
    tiles.emplace_back(new CropTile);
    for (auto const& tile : tiles)
    {
        std::cout << static_cast<int>(tile->whoAmI()) << std::endl;
    }
}

Will output

0
1
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

You can easily do it like that:

class TileBase
{
public:
    enum Type { easyTile, cropTile, waterTile, mediumTile };

    virtual Type whoAmI() const = 0;
    virtual ~TileBase() = default;
};

class EasyTile : public TileBase
{
    Type whoAmI() const override { return easyTile; }    
};

You see, you need to specify the enum Type as return type instead of void.

Ralph Tandetzky
  • 22,780
  • 11
  • 73
  • 120
0
#include <iostream>
using namespace std;

class Tile{
public:
    enum getType { easyTile, cropTile, waterTile, mediumTile};
    virtual getType whoAmI(){}
};
class easyTile:public Tile{
public:
    getType whoAmI(){return getType::easyTile;}
};
class cropTile: public Tile{
public:
    virtual getType whoAmI(){return getType::cropTile;}
};
class waterTile: public Tile{
public:
    virtual getType whoAmI(){return getType::waterTile;}
};
class mediumTile: public Tile{
public:
    virtual getType whoAmI(){ return getType::mediumTile;}
};

int main() {
    Tile *T = new cropTile;
    cout << T->whoAmI() << endl;
    delete T;

    return 0;
}

Output : 1