Sunday, August 13, 2017

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

Object Oriented Programming(OOP) -- when you start to learning programming, this may the first paradigm you will meet. And most explanations of OOP I saw in books or websites, does not explain the real meaning of OOP.

You may see this sort of explanation.
Animals ----- Birds
         +- Fishes
         +- Mammals
'Animals','Fishes','Birds','Mammals' are Class. 'Animals' is a parent Class of other ones. and Birds has a method of 'fly', Fishes has a method of 'swim', and so on.

With this kind of explanation, You can understand the meanings of words 'Class' or 'Method' in abstract concept. But you can't learn the real meanings of C++.

In C++, the 'Class' means the set of data and how to process that.
'How to process that?' is the Class Method.

Let's see some example.
In video game, a player is a typical object.
the Player class is declared like this.

class Player
{
private:
    int pos_x;
    int pos_y;    

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

};

You see the data 'pos_x','pos_y' and methods 'apply_input()','move_to()'.
As you can easily understand, 'pos_x' and 'pos_y' means position of the player.
The method 'apply_input()' applies input data of joystick, 'move_to()' moves the player to specified position.

Simple, isn't it !?

For comparision, let's see the C language implementation of this Player.

struct Player
{
    int pos_x;
    int pos_y;
};

void apply_input(struct Player*, float direction);
void move_to(struct Player*, int x, int y);

In C, struct can not have methods. so we must declare functions outside of the struct, receiving pointer to the struct.

so, class in C++ is the set of data and how to process it.

Would you like to learn more?
Visit the next post.

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...