3

Possible Duplicate:
What's the point of OOP?

What are the advantages of using object-orientated programming over function-orientated.

As a trivial example consider:

struct vector_t {
  int x, y, z;
}

void setVector(vector_t *vector, int _x, int _y, it _z) {
  vector->x = _x;
  vector->y = _y;
  vector->z = _z;
}

vector_t addVector(vector_t* vec1, vector_t* vec2) {
  vector_t vec3;
  vec3.x = vec1->x + vec2->x;
  // and so on...
  return vec3;
}

Now, I am not incredibly familiar with object-orientated programming, but the above would translate to OOP as:

class vector_t {
private:
  int x, y, z;
public:
  void set(int _x, int _y, int _z) { ... };
  int getX() { return x; }
  // ...
  void addVector(vector_t *vec) { ... };
  // ...
};

My question is this? What really makes the second code example so prefered over the first in modern programming? What are the advantages and disadvantages?

Community
  • 1
  • 1
Alexander Rafferty
  • 6,134
  • 4
  • 33
  • 55
  • Duplicate of http://stackoverflow.com/questions/1161930/is-oop-abused-in-universities – Michael Shimmins Sep 13 '10 at 04:57
  • Duplicate of http://stackoverflow.com/questions/24270/whats-the-point-of-oop – Frank Sep 13 '10 at 05:09
  • BTW, it's called object-oriented programming. – Frank Sep 13 '10 at 05:09
  • 4
    Your first example *is* OOP, you're just rolling your own "class" and not using the helpful class syntax. OOP is fundamentally a design pattern, so whether or not it's "preferred" depends on what you're doing. – Seth Sep 13 '10 at 05:19
  • @dehmann: Nah, it's a British-vs-American English difference. In British English, "orientated" is more common than "oriented"; in American English, it's the other way around. – C. K. Young Sep 13 '10 at 05:20
  • 1
    Well I'm australian. I never use the word oriented. – Alexander Rafferty Sep 13 '10 at 05:29
  • Funny, I'm Aussie too, and at Uni it was always referred to as 'oriented'. – Michael Shimmins Sep 13 '10 at 05:42
  • 1
    @Alexander: Yay for boycotting American spelling! (I'm a New Zealander, and though we can have our trans-Tasman rivalries, I'm sure we can work together at least in this instance. :-P) – C. K. Young Sep 13 '10 at 05:49
  • 1
    @Michael: Your uni was obviously brainwashed by American spellers. I bet they never used "spelt" or "learnt" either. :-P – C. K. Young Sep 13 '10 at 05:50

1 Answers1

3

Your first code snippet is actually an example of a poor man's OO implementation in a non-OO language. You're defining an abstract data type (vector_t) and all the operations allowed on it (setVector, addVector, etc), but you're not encapsulating all the data and operations into a single logical unit (i.e. a class). This can be useful if you want or need to use C instead of C++ but still want to have some of the benefits of OOP.

Since you're already doing OOP in both examples, I think it should be obvious why the second code snippet is better.

Mhmmd
  • 1,483
  • 9
  • 15