Here's an example where it may come in handy. Just a simple operation of adding two vectors element by element. Not the best code, it's almost 5am, so you'll have to excuse me.
Code:
// C code
int* add(int * x, int * y,const int n , const int m)
{
if ( n == m)
{
int *z = new int[n];
for ( int i = 0 ; i<n ; i++)
z[i] = x[i] + y[i];
return z;
}
}
const int n = 10;
int a[10] = {something};
int b[10] = {something};;
int * sum;
sum = add(a,b,n,n);
delete [] sum;
You'll probably won't do that: having to remember to deallocate memory for something that got allocated inside a function. See that each vector has its own lengths. It's good to keep length of the array along with its elements. You can do so with struct, but the add function will become a bit wild. With a class, you can spend sometime to design the class vector, such that when it comes time to implement, your user-defined type vector can behave just as any fundamental type.
Code:
// c++ using class
class Vector
{
private:
int num;
int *elem;
public:
Vector():num(0),elem(0) {}
Vector(int n):num(n)
{
elem = new int[num];
for ( int i = 0 ; i < num ; i++)
elem[i] = 0;
}
Vector(int * a, int n = 0): num(n);
{
for ( int i = 0 ; i < num; i++)
elem[i] = a[i];
}
~Vector() {delete [] num}
Vector operator+(const Vector & in) const
{
if ( num == in.num)
{
int temp[num];
for( int i = 0 ; i < num ; i++)
temp[i] = elem[i] + in[i];
return Vector(temp,num);
}
else
exit(0);
}
void operator=(const Vector & in)
{
num = in.num;
if(elem == 0 )
elem = new int[num];
else
{
delete [] elem;
elem = new int[num];
}
for ( int i = 0 ; i < num ; i++)
elem[i] = in[i];
}
operator-;
operator++;
operator--;
operator*;
operator*=;
operator+=;
};
int main()
{
Vector a({some_array},10);
Vector b({some_array},10);
Vector c;
c = a+b;
}
First, notice the destructor ~Vector, it do the deallocation for me. I don't need to remember to call "delete". Even though the class is kinda of long, the implementation is simple. Adding two vector using the same syntax as adding two fundamental type. So if you're a user, and you need to add two vector element by element, you don't really need to check whether you'll have to use array or pointer to represent the array; don't have to remember to deallocate memory. Class let you design your own data type that can behave as close to the fundamental types as possible and more.