C++: Simple Classes

Looking for in-depth C tutorials? Try SourceCrunch.

Classes are an important concept in Object Orientated Programming, and in this tutorial we will learn about classes in C++. I like to think of a class as a set of blueprints - it represents certain variable properties and certain functions that a certain thing has. We can classify things to be in a certain class, and these things will possess the properties that the blueprint specifies. If we take a more "real world" look at this concept - we might create a class which we name "Car". All cars we created which were a member of this group of things would then possess certain properties - for example having a certain colour and engine type, as well as being able to turn on and drive.

Classes behave almost exactly like this in C++. We can create a set of functions and variables which essentially act as blueprints, and then we can create objects (like different types of cars), which abide to these blueprints and put values in to the properties which objects of the class possess (for example, a particular car might be red).

Classes are defined in C++ by using the class keyword followed by the class name, and then some curly brackets, with the closing curly bracket being followed by a semicolon to show the end of the class declaration. The stuff inside the curly brackets is where things get a bit more complicated, and we'll talk about this in a minute. For now, let's just setup some basic code with what we understand about classes so far - let's, for example, create a class to deal with different types of computers (related data, member functions, etc.):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

using namespace std;

class Computer {
	//Class stuff will go in here
};

int main()
{
	//Some stuff to interact with the class will go here
	return 0;
}

From here, we need to populate our class with properties and functions. As such, we need to decide what properties and functions every member of "Computer" should have. For this simple example, each computer should have a name, amount of RAM, and processor speed, and every computer object should be able to output all of the information about the computer. So we have three values and one function which we want to implement into our "Computer" class.

Before we go and implement these properties and functions, we need to talk about the three access modifiers for classes: public, private, and protected. Public parts of a class can be accessed from anywhere in the program, private parts of a class can only be accessed by the class itself (and friends, we'll learn about this in a later tutorial), and protected parts of classes are a sort of compromise which we won't really talk about right now.

Right now, 'private' and 'protected' sections of classes aren't particularly useful to us because we're planning to do most things through our main function, however I assure you that in real applications of classes in programs, you'll be using them a lot more (when you get to the inheritance tutorial it should make sense). These access modifiers are defined by writing the name of the access modifier followed by a colon, so in our example we can just change our class to be completely public (for now):

1
2
3
4
class Computer {
public:
	//Class stuff will go in here
};

Classes are set to 'private' by default, so setting the access modifier to 'public' like this is necessary. With this access modifier set up, we can now begin to implement the different properties and functions which we wanted any object of our "Computer" class to have. Any variables declared inside the class will simply be variables which each object of the class possesses - so we could create variables for the name, amount of RAM, and processor speed, very easily through something like the following:

1
2
3
4
5
6
class Computer {
public:
	string name;
	int RAM;
	double proc_speed;
};

With the code above, any object of the "Computer" class will have a string "name", an int "RAM", and a double "proc_speed". Remember that these values are not shared between all the class objects, but instead each object has its own instance of these variables with different values. As the variables are in the 'public' section, we can tweak each object's version of them very easily from anywhere in the program, as we will do later on to give each computer the correct properties.

We can also create functions inside of a class - these are often called member functions as each member of the class possesses them, and often they tweak an object's class variables. It's often the case that functions in the 'public' section tweak variables in the 'private' or 'protected' sections. In this case, we can just create a basic function that all "Computer" objects will possess which outputs the "name", "RAM", and "proc_speed". As we are programming this function inside the class, we can just refer to these variables by their names and the member function will get the correct variable for whatever member the function is being called upon. It's actually worth noting that often when functions are called upon objects in programming languages, these functions are called methods. So many would call the things we are creating "methods", however C(++) programmers usually use the term "member functions" as it is less vague.

Class member functions can take parameters like any normal functions too, but in this example we can just create a void function with no parameters which uses cout to output the relevant information:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Computer {
public:
	void output_information()
	{
		cout << "Name: "<< name;
		cout << "\nRAM: "<< RAM;
		cout << "\nProcessor Speed: "<< proc_speed;
		cout << "\n";
	}

	string name;
	int RAM;
	double proc_speed;
};

Now that our basic "Computer" class is complete, the real question is how we can create objects of the class and then perform member functions upon them and access their values. We can do this anywhere in the program after the class has been defined, however for the sake of simplicity in this tutorial we will simply be creating and working on class objects in the main function.

A class object, in C++, can be created much like a regular variable. For the data-type you simply write the class's name, and then you can just write the object's name - so if we wanted to create a few computer objects, we could put the following lines into our main function:

1
2
3
Computer computer_one;
Computer computer_two;
Computer computer_three;

We can then access functions and variables that a given object possesses, at least those inside the 'public' section in this case, by using the . operator on the object's name. So we can access the object's "RAM" by writing object_name.RAM - in this case we might want something like computer_one.RAM. Due to our current setup with everything being of a 'public' access modifier, we can also use this member function to set the values of object variables using the = operator - so we could modify our main function to create two computers and set their properties with something like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
	Computer computer_one;
	computer_one.name = "Work-a-tron 5000";
	computer_one.RAM = 4;
	computer_one.proc_speed = 2.6;

	Computer computer_two;
	computer_two.name = "1080p-Video-Renderer 9001";
	computer_two.RAM = 8;
	computer_two.proc_speed = 3;


	return 0;
}

In the above example, we could then output the values by using cout with things like computer_one.name, however it would be much better to simply use the "output_information" member function which we built into all "Computer" objects! We also perform member functions on objects using the . operator, and just like normal functions, we then have to specify some brackets with parameters (empty in this case):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
	Computer computer_one;
	computer_one.name = "Work-a-tron 5000";
	computer_one.RAM = 4;
	computer_one.proc_speed = 2.6;

	Computer computer_two;
	computer_two.name = "1080p-Video-Renderer 9001";
	computer_two.RAM = 8;
	computer_two.proc_speed = 3;

	computer_one.output_information();
	computer_two.output_information();

	return 0;
}

The full code for the program we have created thus-far would be as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>

using namespace std;

class Computer {
public:
	void output_information()
	{
		cout << "Name: "<< name;
		cout << "\nRAM: "<< RAM;
		cout << "\nProcessor Speed: "<< proc_speed;
		cout << "\n";
	}

	string name;
	int RAM;
	double proc_speed;
};


int main()
{
	Computer computer_one;
	computer_one.name = "Work-a-tron 5000";
	computer_one.RAM = 4;
	computer_one.proc_speed = 2.6;

	Computer computer_two;
	computer_two.name = "1080p-Video-Renderer 9001";
	computer_two.RAM = 8;
	computer_two.proc_speed = 3;

	computer_one.output_information();
	computer_two.output_information();

	return 0;
}

Hopefully you should now have a good understanding of what classes are and how we create them in C++. It might be helpful for you to gain a further understanding into how they're useful be trying to create a basic program which makes good use of them as classes and objects can be utilized in a variety of different ways. A nice idea might be to try to create a basic system for a car sales business in which each model of car has its own object with associated values such as the name, price, and number sold.

Just as a quick note on something you might want to try out - structs are structures in C++ almost identical to classes. The only real difference is that structs default to a 'public' access modifier, and classes default to a 'private' access modifier. Apart from this, the only real difference is that structs are generally used for P.O.D (Plain Old Data) structures, in which you just want to associate a number of values in some encapsulation. Take for example the following basic data encapsulation which could be used in some basic game:

1
2
3
4
struct Player {
	string name;
	int pos_x, pos_y;
};

Just like a class, objects can be made by simply using the struct's name, for example Player pl;.

If you're feeling up for a challenge, try moving all the variables in our (or your own) "Computer" class example into a private: section, and then only set them and get the values of them using different functions. These are often called "get" and "set" functions, and are an extremely common practice when writing classes with private variables.