**I very much dislike that link to ehchua — much of the leading information is just plain wrong.
encapsulation / data hiding
The idea of OO is to
encapsulate data. Well-written procedural code does the same thing.
For example, suppose you have an (x y) point that you wish to maintain. Procedurally, you will create some functions to operate over a point.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
typedef struct
{
double x, y;
}
point;
point point_create( double x, double y )
{
point p;
p.x = x;
p.y = y;
return p;
}
point point_add( point a, point b )
{
return point_create( a.x + b.x, a.y + b.y );
}
| |
And so on. With OO, the functions that operate over your data are treated as part of the data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
struct point
{
double x, y;
point() { }
point( double x, double y )
{
this->x = x;
this->y = y;
}
point add( point a, point b )
{
return point( a.x + b.x, a.y + b.y );
}
};
| |
There are some differences. In C++, I would rather write that addition as an actual ‘+’ operator overload, and I’ll use references instead of a copy of the entire struct:
1 2 3 4 5 6 7 8 9
|
struct point
{
...
point operator + ( const point& a, const point& b )
{
return point( a.x + b.x, a.y + b.y );
}
};
| |
This also makes using the point significantly more idiomatic in code:
1 2 3
|
// C
point a = point_create( 1, 2 );
point s = point_add( a, point_create( 3, 5 ) );
| |
1 2 3
|
// C++
point a( 1, 2 );
point s = a + point( 3, 5 );
| |
These examples, BTW, are
simplistic in the extreme. Consider the extra care that you must take in C to handle dynamic data, for example. In C++, RAII is automatic (assuming you use it).
Design Rationale Behind Object Oriented Programming
OOP takes it a little further. The primary principles behind OOP include:
• encapsulation (bundling data with operations on that data)
• data abstraction (internals are hidden behind the API)
• polymorphism (inheritance)
• dynamic binding (virtual functions)
None of these are things that can’t be done in C, and almost as easily. But as part of the C++ language you get it for free, without having to write all the boilerplate yourself and leaving actual code looking clean and readable.
It isn’t perfect
In spite of what you may read, OOP is not the One True Way™. As has always been the case, many, many poorly-written and bloated code is written in OOP as is procedural.
Because of the way it is designed, some problems manifest more in one methodology than the other, but the problem with, say, code that knows too much about its environment (such as is often simplified into anti-global variable sentiment) exists just as commonly in OOP as procedural environments.
Whether using an OOP methodology or not, the important point is to design your code properly. That takes careful effort to learn, and is frighteningly uncommon in real-world code. (IMHO)