Programming & Scripting Tutorials

C++: Simple Classes





A question I often get from viewers of this site is "What are classes used for, and how do I use them?". Classes can usually be replaced by direct access to the variable or content of the class, but using classes does not only tidy up the code; It also can fix bugs and potential security issues (as you can imagine direct access makes it easy for hackers).

Classes in C++ are actually fairly easy to use. Classes can be declared as "class" or "struct"; I suggest you have a read through this script to figure out how classes work:

#include <iostream>

using namespace std;

class Ball
{
public:
	int size;
	double bounciness;
};

int main(){
	Ball MyBall = {5, 9.32};
	cout << "Size: " << MyBall.size << endl;
	cout << "Bounciness: " << MyBall.bounciness << endl;
system("PAUSE");
return 0;
}
Download
When I first looked at classes I was confused at how "Ball MyBall = {5, 9.32}" could relate directly to the class variables size and bounciness, however as you will see if you switch the order in which they are declared the values will swap around, as it is all on the order in which they have been declared. There are two main types of members in classes, public and private.
However if you change the code around to say private instead of public you should get some errors which say something like the following:

cannot access private member declared in class 'Ball'

This is because public members can be accessed by anything, from any context, Private members however are like things you put inside your safe. You don't let anybody just go inside your house and look inside it; Only other member functions of the class can access private stuff. You will learn more about privates as you read code with them in, in later lessons.

Also don't forget that you can specify classes in header files.

This C++ tutorial was written by


Back to C++

Advertisement: