You are told OOP is significantly different than procedural programming.
It isn’t.
Procedurally, you create things (objects) and then have functions that operate on those objects.
In OOP, the functions that operate on objects are just
part of the object.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
struct point
{
double x, y;
};
point create_point( double x, double y )
{
point p;
p.x = x;
p.y = y;
return p;
}
void add_point( point& a, point b )
{
a.x += b.x;
a.y += b.y;
}
etc
|
struct point
{
double x, y;
point( double x, double y )
{
this->x = x;
this->y = y;
}
void add( point b )
{
this->x += b.x;
this->y += b.y;
}
etc
}; |
They get used similarly:
1 2 3 4 5
|
int main()
{
point p = create_point( -7, 3.1415926 );
add_point( p, create_point( 2, 0 ) );
cout << p.x << "," << p.y << "\n";
|
int main()
{
point p { -7, 3.1415926 };
p.add( point( 2, 0 ) );
cout << p.x << "," << p.y << "\n"; |
What OOP provides you, though, is additional super powers over resource management.
For example, in C, playing with files requires careful awareness of whether or not your program has an open file handle:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
FILE* fp = fopen( "somefile.csv", "r" );
if (!fp) return false;
int foo, bar, baz;
if (!fscanf( fp, "%d %d %d", &foo, &bar, &baz ))
{
fclose( fp );
return false;
}
if (...)
{
fclose( fp );
do_some_other_cleanup();
return false;
}
...
// everything's good, phew...
fclose( fp );
return true;
|
C++
encapsulates all that worry into the object's automatic destructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
std::ifstream f( "somefile.csv" );
if (!f) return false;
int foo, bar, baz;
f >> foo >> bar >> baz;
if (!f) return false;
if (...)
return false;
...
// finally...
return true;
|
The convenience here is that the fstream object knows how to clean up after itself.
OOP also provides you with better control over what your users can do with your objects. In procedural programming you have to go through some extraordinary measures to hide information the user shouldn't be touching. Most of the time, you just have a comment that says "don't touch this" and hope your users don't. (They do.)
OOP lets you mark stuff as “public” or “private” (or “protected”, which is private to everything except derived classes).
This is part of
information hiding and
data abstraction.
There’s more, but that should get you started.
Don’t think of OOP as evil. It is just looking at things from a slightly different angle. Consider if the “point” class above were a “matrix”. Complete with operator overloads, you can very easily create matrices.
Hope this helps a little...