Skip to main content
Became Hot Network Question
edited tags; edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

Object-oriented programming OOP demonstration in C++17 using a Pokémon

Source Link
greg
  • 1k
  • 1
  • 9
  • 14

Object-oriented programming in C++17

I want to showcase with as minimal code as possible the basic Object-oriented programming (OOP) principles of Polymorphism, Inheritance, and Encapsulation. I know there are many more principles than just these 3 and even different types of the 3 I've mentioned there. I attempted to implement them all below. I think using Pokémon as an example is a good way to show this, so I've used Castform as my buddy of choice for these examples.

If you believe showcasing more than just Polymorphism, Inheritance, and Encapsulation to evaluate a developers understanding of OOP, please provide comments around this and which additional key principles I should add to my Pokémon example.

Main.cpp

#include <iostream>
#include <string>
#include <time.h>

class Pokemon
{
    protected:
        int m_dex_num;
        float m_catch_rate;
        std::string m_type;
    public:
        Pokemon(int dex_num, int catch_rate, std::string type)
            : m_dex_num(dex_num), m_catch_rate(catch_rate), m_type(type) {}

        int dex_num() const { return m_dex_num; }
        float catch_rate() const { return m_catch_rate; }
        std::string type() const { return m_type; }

        virtual bool attempt_catch() = 0;
};

class Castform : public Pokemon
{
    private:
        std::string m_forms[3] = { "sunny", "rainy", "snowy" };
    public:
        Castform() : Pokemon(351, 11.9, "normal") {}

        bool attempt_catch() {
            srand(time(NULL));
            return (rand() % 100) < m_catch_rate;
        }
};

int main()
{
    auto wild_castform = Castform();

    std::cout << "Wild Castform appeared!\n";
    std::cout << "Dex number " << wild_castform.dex_num() << '\n';
    std::cout << "It's a " << wild_castform.type() << " type\n";

    for(int i=0; i < 5; ++i) {
            std::cout << "Catch attempt resulted in " << wild_castform.attempt_catch() << '\n';
    }

    return 0;
}

c++