int a = 5, b = 10;
int sum (int a, int b) {
return a + b;
}
int average (int a, int b) {
return (a + b) / 2;
}
int a = 5, b = 10;
cout << sum(a, b); // prints 15
cout << average(a, b); // prints 7
int a = 5, b = 10;
int c = 13, d = 76;
int e = 54, f = 14;
int g = 12, h = 5;
int i = 87, j = 2;
cout << sum(a, b);
cout << sum(c, d);
cout << average(e, f);
cout << sum(g, h);
cout << average(i, j);
int number_pairs[5][2] = {
{5, 10},
{13, 76},
{54, 14},
{12, 5},
{87, 2}
};
cout << sum(a[0][0], a[0][1]);
cout << sum(a[1][0], a[1][1]);
cout << average(a[2][0], a[2][1]);
cout << sum(a[3][0], a[3][1]);
cout << average(a[4][0], a[4][1]);
Moreover, what if you changed your mind and decided to use 3-4 numbers in each pair?
Would you go back and change the arguments you pass in each function call?
That's where object oriented programming comes in the scene!
class NumberPair {
};
Notice how a semicolon is required even after the curly braces. We'll look at why it's required later.class NumberPair {
int a, b;
};
class NumberPair {
private:
int a, b;
};
The 'private' label is used for specifying so. If you don't provide any label, it's automatically considered as private though. Adding this label wasn't necessary but still we did it anyway as it's a good practice and makes it more apparent.
For now, keep in mind that private variables/functions can't be accessed outside of the class.
class NumberPair {
private:
int a, b;
public:
int sum () {
return a + b;
}
int average () {
return (a + b) / 2;
}
};
Note that the arguments weren't necessary as the integers, a and b, were accessible to all functions within the class.NumberPair pair1; // CLASSNAME OBJECTNAME;
NumberPair pair2;
The code above will create two objects 'pair1' and 'pair2' which belongs to the class 'NumberPair.'
If you didn't get the syntax, here's the generalized version:
CLASSNAME OBJECTNAME;
Ofc, replace CLASSNAME with the actual class of your class. OBJECTNAME can be any valid name such as 'tuna.'
NumberPair pair1 (5, 10);
NumberPair pair2 (3, 5);
You can use specify the numbers in parenthesis as argument just like you do with functions.class NumberPair {
private:
int a, b;
public:
// CONSTRUCTOR
NumberPair (int num1, int num2) {
// receive the numbers and set them to the class variables
a = num1;
b = num2;
}
int sum () {
return a + b;
}
int average () {
return (a + b) / 2;
}
};
Note that the name of the constructor is exactly same as the class name. Your compiler is smart enough to identify the constructor as a function which has the same name as the class name.
Note that constructors cannot return anything, thus return type shouldn't be specified, not even 'void.'
Here, the constructor just simply sets the values of 'a' and 'b' to the values provided when objects are made out of the class.
NumberPair a(10, 5), b(3, 5); // 2 objects are created, a and b respectively
cout << a.sum(); // 15
cout << b.average(); // 4
cout << b.sum(); // 8
No longer a dirty mess!