OOP demonstration in C++17 using a PokémonPHP OOP example using animal classes

Scaling an object to change its key

`Table the `LCM` of an increasing list

I just entered the USA without passport control at Atlanta airport

What does this Swiss black on yellow rectangular traffic sign with a symbol looking like a dart mean?

reverse a call to mmap()

Math symbols in math operators

Is Newton's third law really correct?

Old time bike. Can I put a rear derailleur?

What is this word in a sample of blackletter script?

What jobs would people work in a frontier railroad town?

How to modify a string without altering its text properties

First occurrence in the Sixers sequence

Why things float in space, though there is always gravity of our star is present

Explicit song lyrics checker

Examples of protocols that are insecure when run concurrently

How could I create a situation in which a PC has to make a saving throw or be forced to pet a dog?

How can the US president give an order to a civilian?

Teferi's Time Twist and Gideon's Sacrifice

Are intrusions within a foreign embassy considered an act of war?

Does Snape have a bad hairstyle according to the wizarding world?

I found a password with hashcat but it doesn't work

King or Queen-Which piece is which?

Leaving job close to major deadlines

How to make all magic-casting innate, but still rare?



OOP demonstration in C++17 using a Pokémon


PHP OOP example using animal classes






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6












$begingroup$


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() << " typen";

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


return 0;



c++










share|improve this question











$endgroup$


















    6












    $begingroup$


    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() << " typen";

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


    return 0;



    c++










    share|improve this question











    $endgroup$














      6












      6








      6


      2



      $begingroup$


      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() << " typen";

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


      return 0;



      c++










      share|improve this question











      $endgroup$




      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() << " typen";

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


      return 0;



      c++







      c++ object-oriented random c++17 pokemon






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 1 at 17:10









      200_success

      134k21166439




      134k21166439










      asked Jun 1 at 16:42









      greggreg

      532310




      532310




















          1 Answer
          1






          active

          oldest

          votes


















          7












          $begingroup$

          • It looks like all the Pokemon member variables should be private, not public.


          • The Pokemon constructor takes catch_rate as an int, where it should be a float.


          • The Pokemon constructor could std::move the string argument into m_type.


          • Pokemon::type() could return by const& to avoid an unnecessary copy.


          • Castform::m_forms is not used anywhere, but should probably also be static and const.



          • When overriding a virtual function, we should always use the override keyword (and arguably also the virtual keyword):



            virtual bool attempt_catch() override ... 


          • Use the C++11 <random> functionality, not rand().



          Run-time polymorphism with virtual functions in C++ is driven by a need to treat objects of different types with the same interface. Unfortunately, this example lacks the motivation for it:



          • Currently the attempt_catch() function could be implemented in the Pokemon base-class with no problem.


          • There is no example of differing behavior (i.e. there should be a second pokemon type implementing a different attempt_catch() function). Maybe an attack function would work better?



          • There is no demonstration of using the different types through the same interface. In C++ this usually boils down to storing different types in the same container (e.g. iterating a std::vector<std::unique_ptr<Pokemon>> and calling the virtual function). However, it might be simpler to pass two different pokemon types to a function taking a Pokemon reference:



            void throw_pokeball(Pokemon const& target) target.attempt_catch() // or something



          Depending on what this is actually for, I'd suggest approaching things in a "problem -> solution" way, both in terms of what the code does (see above), but also in terms of language development and why these features exist. i.e.



          • "Here's what programmers used to have to do without this language feature [...]. It sucks because [...]"


          • "This language feature allows us to do [...] safely and easily because [...]".



          Note that there are many different types of both static and dynamic polymorphism in C++ (e.g. function overloading, implicit conversions, function objects, template parameters (traits, tags, etc.)), not just inheritance and virtual functions.






          share|improve this answer









          $endgroup$












          • $begingroup$
            Using std::move on the string argument into m_type in the Pokemon ctor would avoid another unnecessary string copy correct?
            $endgroup$
            – greg
            Jun 3 at 18:37











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f221497%2foop-demonstration-in-c17-using-a-pok%25c3%25a9mon%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          7












          $begingroup$

          • It looks like all the Pokemon member variables should be private, not public.


          • The Pokemon constructor takes catch_rate as an int, where it should be a float.


          • The Pokemon constructor could std::move the string argument into m_type.


          • Pokemon::type() could return by const& to avoid an unnecessary copy.


          • Castform::m_forms is not used anywhere, but should probably also be static and const.



          • When overriding a virtual function, we should always use the override keyword (and arguably also the virtual keyword):



            virtual bool attempt_catch() override ... 


          • Use the C++11 <random> functionality, not rand().



          Run-time polymorphism with virtual functions in C++ is driven by a need to treat objects of different types with the same interface. Unfortunately, this example lacks the motivation for it:



          • Currently the attempt_catch() function could be implemented in the Pokemon base-class with no problem.


          • There is no example of differing behavior (i.e. there should be a second pokemon type implementing a different attempt_catch() function). Maybe an attack function would work better?



          • There is no demonstration of using the different types through the same interface. In C++ this usually boils down to storing different types in the same container (e.g. iterating a std::vector<std::unique_ptr<Pokemon>> and calling the virtual function). However, it might be simpler to pass two different pokemon types to a function taking a Pokemon reference:



            void throw_pokeball(Pokemon const& target) target.attempt_catch() // or something



          Depending on what this is actually for, I'd suggest approaching things in a "problem -> solution" way, both in terms of what the code does (see above), but also in terms of language development and why these features exist. i.e.



          • "Here's what programmers used to have to do without this language feature [...]. It sucks because [...]"


          • "This language feature allows us to do [...] safely and easily because [...]".



          Note that there are many different types of both static and dynamic polymorphism in C++ (e.g. function overloading, implicit conversions, function objects, template parameters (traits, tags, etc.)), not just inheritance and virtual functions.






          share|improve this answer









          $endgroup$












          • $begingroup$
            Using std::move on the string argument into m_type in the Pokemon ctor would avoid another unnecessary string copy correct?
            $endgroup$
            – greg
            Jun 3 at 18:37















          7












          $begingroup$

          • It looks like all the Pokemon member variables should be private, not public.


          • The Pokemon constructor takes catch_rate as an int, where it should be a float.


          • The Pokemon constructor could std::move the string argument into m_type.


          • Pokemon::type() could return by const& to avoid an unnecessary copy.


          • Castform::m_forms is not used anywhere, but should probably also be static and const.



          • When overriding a virtual function, we should always use the override keyword (and arguably also the virtual keyword):



            virtual bool attempt_catch() override ... 


          • Use the C++11 <random> functionality, not rand().



          Run-time polymorphism with virtual functions in C++ is driven by a need to treat objects of different types with the same interface. Unfortunately, this example lacks the motivation for it:



          • Currently the attempt_catch() function could be implemented in the Pokemon base-class with no problem.


          • There is no example of differing behavior (i.e. there should be a second pokemon type implementing a different attempt_catch() function). Maybe an attack function would work better?



          • There is no demonstration of using the different types through the same interface. In C++ this usually boils down to storing different types in the same container (e.g. iterating a std::vector<std::unique_ptr<Pokemon>> and calling the virtual function). However, it might be simpler to pass two different pokemon types to a function taking a Pokemon reference:



            void throw_pokeball(Pokemon const& target) target.attempt_catch() // or something



          Depending on what this is actually for, I'd suggest approaching things in a "problem -> solution" way, both in terms of what the code does (see above), but also in terms of language development and why these features exist. i.e.



          • "Here's what programmers used to have to do without this language feature [...]. It sucks because [...]"


          • "This language feature allows us to do [...] safely and easily because [...]".



          Note that there are many different types of both static and dynamic polymorphism in C++ (e.g. function overloading, implicit conversions, function objects, template parameters (traits, tags, etc.)), not just inheritance and virtual functions.






          share|improve this answer









          $endgroup$












          • $begingroup$
            Using std::move on the string argument into m_type in the Pokemon ctor would avoid another unnecessary string copy correct?
            $endgroup$
            – greg
            Jun 3 at 18:37













          7












          7








          7





          $begingroup$

          • It looks like all the Pokemon member variables should be private, not public.


          • The Pokemon constructor takes catch_rate as an int, where it should be a float.


          • The Pokemon constructor could std::move the string argument into m_type.


          • Pokemon::type() could return by const& to avoid an unnecessary copy.


          • Castform::m_forms is not used anywhere, but should probably also be static and const.



          • When overriding a virtual function, we should always use the override keyword (and arguably also the virtual keyword):



            virtual bool attempt_catch() override ... 


          • Use the C++11 <random> functionality, not rand().



          Run-time polymorphism with virtual functions in C++ is driven by a need to treat objects of different types with the same interface. Unfortunately, this example lacks the motivation for it:



          • Currently the attempt_catch() function could be implemented in the Pokemon base-class with no problem.


          • There is no example of differing behavior (i.e. there should be a second pokemon type implementing a different attempt_catch() function). Maybe an attack function would work better?



          • There is no demonstration of using the different types through the same interface. In C++ this usually boils down to storing different types in the same container (e.g. iterating a std::vector<std::unique_ptr<Pokemon>> and calling the virtual function). However, it might be simpler to pass two different pokemon types to a function taking a Pokemon reference:



            void throw_pokeball(Pokemon const& target) target.attempt_catch() // or something



          Depending on what this is actually for, I'd suggest approaching things in a "problem -> solution" way, both in terms of what the code does (see above), but also in terms of language development and why these features exist. i.e.



          • "Here's what programmers used to have to do without this language feature [...]. It sucks because [...]"


          • "This language feature allows us to do [...] safely and easily because [...]".



          Note that there are many different types of both static and dynamic polymorphism in C++ (e.g. function overloading, implicit conversions, function objects, template parameters (traits, tags, etc.)), not just inheritance and virtual functions.






          share|improve this answer









          $endgroup$



          • It looks like all the Pokemon member variables should be private, not public.


          • The Pokemon constructor takes catch_rate as an int, where it should be a float.


          • The Pokemon constructor could std::move the string argument into m_type.


          • Pokemon::type() could return by const& to avoid an unnecessary copy.


          • Castform::m_forms is not used anywhere, but should probably also be static and const.



          • When overriding a virtual function, we should always use the override keyword (and arguably also the virtual keyword):



            virtual bool attempt_catch() override ... 


          • Use the C++11 <random> functionality, not rand().



          Run-time polymorphism with virtual functions in C++ is driven by a need to treat objects of different types with the same interface. Unfortunately, this example lacks the motivation for it:



          • Currently the attempt_catch() function could be implemented in the Pokemon base-class with no problem.


          • There is no example of differing behavior (i.e. there should be a second pokemon type implementing a different attempt_catch() function). Maybe an attack function would work better?



          • There is no demonstration of using the different types through the same interface. In C++ this usually boils down to storing different types in the same container (e.g. iterating a std::vector<std::unique_ptr<Pokemon>> and calling the virtual function). However, it might be simpler to pass two different pokemon types to a function taking a Pokemon reference:



            void throw_pokeball(Pokemon const& target) target.attempt_catch() // or something



          Depending on what this is actually for, I'd suggest approaching things in a "problem -> solution" way, both in terms of what the code does (see above), but also in terms of language development and why these features exist. i.e.



          • "Here's what programmers used to have to do without this language feature [...]. It sucks because [...]"


          • "This language feature allows us to do [...] safely and easily because [...]".



          Note that there are many different types of both static and dynamic polymorphism in C++ (e.g. function overloading, implicit conversions, function objects, template parameters (traits, tags, etc.)), not just inheritance and virtual functions.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jun 1 at 19:29









          user673679user673679

          4,23711332




          4,23711332











          • $begingroup$
            Using std::move on the string argument into m_type in the Pokemon ctor would avoid another unnecessary string copy correct?
            $endgroup$
            – greg
            Jun 3 at 18:37
















          • $begingroup$
            Using std::move on the string argument into m_type in the Pokemon ctor would avoid another unnecessary string copy correct?
            $endgroup$
            – greg
            Jun 3 at 18:37















          $begingroup$
          Using std::move on the string argument into m_type in the Pokemon ctor would avoid another unnecessary string copy correct?
          $endgroup$
          – greg
          Jun 3 at 18:37




          $begingroup$
          Using std::move on the string argument into m_type in the Pokemon ctor would avoid another unnecessary string copy correct?
          $endgroup$
          – greg
          Jun 3 at 18:37

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f221497%2foop-demonstration-in-c17-using-a-pok%25c3%25a9mon%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to write a 12-bar blues melodyI-IV-V blues progressionHow to play the bridges in a standard blues progressionHow does Gdim7 fit in C# minor?question on a certain chord progressionMusicology of Melody12 bar blues, spread rhythm: alternative to 6th chord to avoid finger stretchChord progressions/ Root key/ MelodiesHow to put chords (POP-EDM) under a given lead vocal melody (starting from a good knowledge in music theory)Are there “rules” for improvising with the minor pentatonic scale over 12-bar shuffle?Confusion about blues scale and chords

          What if the end-user didn't have the required library?What is setup.py?What is a clean, pythonic way to have multiple constructors in Python?What does Ruby have that Python doesn't, and vice versa?What is the reason for having '//' in Python?How do I create a namespace package in Python?How to package shared objects that python modules depend on?setuptools vs. distutils: why is distutils still a thing?Navigation in Windows 10 vs code not going to virtualenv library when the same library is installed at user levelPython create package for local usePackaging a project that uses multiple python versionsWhy is permission denied on pip install except for when “--user” is included at end of command?

          Esgonzo ibérico Índice Descrición Distribución Hábitat Ameazas Notas Véxase tamén "Acerca dos nomes dos anfibios e réptiles galegos""Chalcides bedriagai"Chalcides bedriagai en Carrascal, L. M. Salvador, A. (Eds). Enciclopedia virtual de los vertebrados españoles. Museo Nacional de Ciencias Naturales, Madrid. España.Fotos