Jul 17, 2013 at 8:54am UTC
I don't really get when or why to use classes, to me it just seems like, bear in mind though that I am a beginner, you can accomplish the same things as you can with classes in simpler ways. Here is an example of calculating the faculty. Why would I want to do it like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
using namespace std;
class faculty{
public :
void calculatingFaculty(int *);
};
void faculty::calculatingFaculty(int * number){
for (int x=*number;x>1;x--){
*number *= (x-1);
}
}
int main(){
int integer;
cout << "Enter the integer which you want to calculate the faculty of: " ; cin >> integer;
faculty objectTest;
objectTest.calculatingFaculty(&integer);
cout << integer << endl;
}
When I can do it in a shorter way, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
using namespace std;
void calculatingFaculty(int * number){
for (int x=*number;x>1;x--){
*number *= (x-1);
}
}
int main(){
int integer;
cout << "Enter the integer which you want to calculate the faculty of: " ; cin >> integer;
calculatingFaculty(&integer);
cout << integer << endl;
}
Or even shorter, like this:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
using namespace std;
int main(){
int integer;
cout << "Enter the integer which you want to calculate the faculty of: " ; cin >> integer;
for (int x=integer;x>1;x--){
integer *= (x-1);
}
cout << integer << endl;
}
I understand that the intention of classes maybe isn't to use them for simple programs like this, but this is just an example.
Last edited on Jul 17, 2013 at 8:56am UTC
Jul 17, 2013 at 9:03am UTC
You really don't need to use classes for small things like that. That's just OOP overkill and wastes your time.
But, you will need classes for larger projects such as games and databases, server software, etc.
Try making a simple text based rpg without classes, then try doing with them.
Jul 17, 2013 at 9:09am UTC
Okay, but I still don't get why to make some things in a class private, why can't you make it all public?
Jul 17, 2013 at 9:20am UTC
It is for encapsulation. generally you want to prevent unauthorized access to your variables.
Jul 17, 2013 at 9:38am UTC
How could someone, or rather something else, access my variables except for myself? Because in order to get access of them you have to call them. Is what you're saying that those variables could accidentally get called if you don't make them private?