Sunday, August 13, 2017

What is OOP(Object Oriented Programmming)?? -- the real meaning in C++ - 2/2

In previous post, We learn meanings of Class, Methods in C++,which is the set of data and how to process that.

And see the simple video game's Player class in C++ like

class Player
{
private:
    int pos_x;
    int pos_y;    

public:
    void apply_input(float direction);
    void move_to(int x, int y);
};

Ok next, we will make class Enemy.

class Enemy
{
private:
    int hate;
    int pos_x;
    int pos_y;    

public:
    void apply_hate(int hate);
    void move_to(int x, int y);
};

Class Enemy does not require 'apply_input()' method because it will not move by joystick input.
And Enemy has hate data(declared as int to make it simple), which will used for enemy's behaviour.

mmm... It seems to be OK, but the Player and Enemy has same data and methods.
It's waste of codes.

Let's think about 'pos_x' and 'pos_y'.
These are attributes of all object in the game.
So we declare Object class which have position data and related method.

class Object
{
private:
    int pos_x;
    int pos_y;
public:
    void move_to(int x, int y);
};

and the class Player and Enemy 'Inherits' the class Object.

class Player : public Object
{
public:
    void apply_input(float direction);
};

class Enemy : public Object
{
private:
    int hate;
public:
    void apply_hate(int hate);
};

Inheritance in C++ means addition of data and methods.
In this example, Object has position of object.
And in addition, Player has method 'apply_input', Enemy has data 'hate' and a method 'apply_hate()'.

Inheritance is usable when some code is common in some classes.



No comments:

Post a Comment

It's magic! std::bind

'std::bind' is a powerful helper for working around 'std::function'. 'std::bind' makes a instance of 'std::fun...