Lab 8 — C++ programming
Template for Lab 8. Programming in C++.
Classes in C++
Classes have their declarations in header files, given either a .h file extension or a
.hpp file extension to show that it's specifically a C++ header file. You would lay out a class in a
header file like,
for example:
// myclass.hpp
#ifndef __MY_CLASS_HPP__
#define __MY_CLASS_HPP__
class MyClass {
// everything that follows `public` is callable or usable outside the class
public:
// default constructor (initializes class with no parameters)
MyClass();
// constructor that takes an argument
MyClass(int x);
// destructor (prefixed with a `~`). destructors never take
// parameters
~MyClass();
// public member functions go here
void my_function();
// const means member variables of the class are unmodified
// by this function call
void my_const_function() const;
// everything that follows `private` is called or used only within the class:
private:
// private member functions and member variables go here.
void my_private_function();
// best practice is to prefix variables with something to show
// that they come from the class definition when used in
// functions
int _x;
};
#endif // __MY_CLASS_HPP__
My best practice for ordering declarations in classes is: constructors at the top, public member functions, private member functions, public member variables (ideally you don't have any), private member variables. There is no enforcement of this by the compiler, but it's ordered by what I care about most to least when reading the code for a class.1
Then in a separate source code file, you can write the definitions for each member function. C++ puts
every function declared in your class in a namespace (just like std::), so you
have to prefix each function with the name of your class like so:
// myclass.cpp
#include "myclass.hpp"
// colon after parameter list of a constructor is a list of member
// variables and what to initialize them to
MyClass::MyClass() : _x(0) {
}
MyClass::MyClass(int x) : _x(x) {
}
MyClass::~MyClass() {
}
void MyClass::my_function() {
int x = 5;
_x += x; // modify the member variable `_x`
}
void MyClass::my_const_function() const {
int x = 5;
x += 5; // modify a variable declared in the function.
// fine because this has no effect on the class's
// member variables
}
void MyClass::my_private_function() {
// do something that outside users of my class shouldn't do
// directly
}
The usage of the class would then look something like this:
MyClass my_class(); // calls the default constructor
MyClass my_class2(6); // calls the constructor that takes a parameter
const MyClass my_class_const(7); // creates an immutable version of my class
// class declared without const can call both functions
my_class.my_function();
my_class.my_const_function();
// class declared const can only call const functions
my_class_const.my_const_function();
// when all three objects go out of scope, their destructors are called