Chris Gregory

Home Blog LinkedIn Github

C++ Tutorial 8 - Classes

12/19/2016

Here we will go over making a class.

#include <cstdio>

using namespace std;

class integer {};

int main() {
    /* Visual Studio: */ getchar();
    return 0;
}

To define a class, use the syntax class my_class_name {};. Our integer class is going to have a member int that we are going to provide methods to interact with.

To add a member int named value, add int value; inside the curly brackets of the class. Now make an integer variable inside main().

class integer { int value; };

int main() {
    integer i;

    ...
}

By default, all members and methods of classes are private, meaning that they can only be accessed from within the class. So our member variable we've named value is useless right now. We need to define a function called get() that will retrieve the value, and set() that will set the value. We need to first declare these functions, and then separately define them. Here we will declare them:

class integer {
    int value;

    int get();
    void set(int new_value);
};

These methods are still private. To make them public, add public: between the member variable and the methods:

class integer {
    int value;
public:
    int get();
    void set(int new_value);
};

Now we will define them, outside of the class body:

int integer::get() { return value; }
void integer::set(int new_value) { value = new_value; }

The special syntax integer:: tells the computer that the function is a method of the class integer.

Now we can try using our integer class.

#include <iostream>

int main() {
    integer i;
    i.set(3);
    // prints "3"
    cout << i.get() << "\n";

    const integer two = 2;
    cout << copy.get() << "\n";

    ...
}

Uh oh, our integer class gives an error when we try to initialize it with the value 2. We are trying to use a special method, the constructor, when we haven't defined one. We are also trying to use the get() method on a const integer, when we haven't told the computer that is allowed.

Here is how to write the constructor. Put the following line inside the class:

    integer(int initial_value);

Then define it outside the class:

integer::integer(int initial_value) : value(initial_value) {}

We explicitly call the int's constructor with our initial_value parameter by using the colon (:) initializer syntax.

Now we need to make the get() method work on a const integer. To do this we add the keyword const to the description of this method. We change it both in the declaration and the definition:

    // in class integer:
    int get() const;
// outside the class integer:
int integer::get() const { return value; }