Classes are user defined types that allow you to model real world objects.
Classes are normally split into two files. A header file which holds the class declaration and a cpp file that houses the class definition.
cube.h:
#ifndef CUBE_H
#define CUBE_H
#include <memory>
class Cube {
public:
Cube();
Cube(int length, int width, int height);
~Cube();
int get_length() const;
int get_width() const;
int get_height() const;
int area() const;
int volume() const;
protected:
std::unique_ptr<int> m_length;
private:
std::unique_ptr<int> m_width;
std::unique_ptr<int> m_height;
};
#endif
The header file houses the class declaration. Classes are defined using the class keyword followed by the name, usually in Pascal case. They have private, protected and public properties. Their properties are private by default. When you use an access modifier, it remains in effect until another modifier is reached.
- Private properties are accessible only in the class itself.
- Protected properties are available in the class and any sub-classes.
- Public properties are available anywhere.
If you break the access rules, you will get a compiler error.
The properties can be either methods, which are functions bound to the class or attributes which are variables bound to an instance.
Notice that the get* methods are declared as const. This indicates to the compiler that they will not change the attributes of the class. This means that if we declare an instance as const, these methods can still be called.
cube.cpp
#include "Cube.h"
Cube::Cube() : Cube {0, 0, 0} {}
Cube::Cube(int length, int width, int height) {
m_length = std::make_unique<int>(length);
m_width = std::make_unique<int>(width);
m_height = std::make_unique<int>(height);
}
Cube::~Cube() {}
int Cube::get_length() const {
return *m_length;
}
int Cube::get_width() const {
return *m_width;
}
int Cube::get_height() const {
return *m_height;
}
int Cube::area() const {
return *m_length * *m_width;
}
int Cube::volume() const {
return area() * *m_height;
}
The cpp file holds the class definition, the implementation of the class. The signature of the method must be marked with the name of the class and the scope resolution operator before the function name. This tells the compiler that the function is actually a method in the class.
main.cpp
#include <iostream>
#include "Cube.h"
int main() {
Cube cube1;
Cube cube2 {2, 1, 1};
std::cout << "Cube1: " << cube1.area() << ", " << cube1.volume() << std::endl;
std::cout << "Cube2: " << cube2.area() << ", " << cube2.volume() << std::endl;
return 0;
}
You access public properties and methods using the . operator for non-pointer variables and the arrow operator (->) for pointer variables. If you create a const variable, pointer, or reference, you will not be able to call any method that isn’t marked as const.
A struct is exactly the same as a class but the members are public by default.