C++ Classes

We already know about structs which bring together several variables that describe a "thing." However, to implement functions, we'd have to pass the struct by value.

In the object oriented way, we prefer to have related functionality (print_rectangle, area for a rectangle class) be part of the object (the struct)

What is a class

Writing C++ Classes

const modifier

void print() const {
	...
}

Examples

In-lining example:

// rectangle.h
#ifndef RECTANGLE_H
#define RECTANGE_H

class Rectangle {
	...
	double area() const {
	// in-lining
	return width*height;
	}
	...
};
#endif //RECTANGLE_H

Defining a function outside class:

// rectangle.h
#ifndef RECTANGLE_H
#define RECTANGLE_H

class Rectangle {
	...
	double area() const;
	...
}
#endif //RECTANGLE_H
// rectangle.cpp
#include "rectangle.h"

double Rectangle::area() const {
	//define outside class
	return width * height;
}

class2.cpp:

#include <iostream>

class Rectangle {
public:
	double width;
	double height;
	
	void print() const {
		std::cout << "width=" << width << ", height=" << height << std::endl;
	}
	
	double area() const {
		return width*height;
	}
};

int main() {
	Rectangle r = {30.0, 40.0};
	r.print();
	std::cout << "area=" << r.area() << std;;endl;
	return 0;
}

Protection

Fields and member functions can be public, private, or protected.

How to section:

class Rectangle {
public:
	...
	double area() const {
	//definition inside class
	return width * height;
	}
	...
private:
	double width, height;
};

\

this pointer

When another member function has a parameter with the same name as the instance variable it is supposed to initialize, the local variable (parameter) will hide the instance variable.
this is a pointer to the instance variable and can be used to clarify.

We don't use this unless necessary in C++, unlike Java, where it is a good style to always qualify instance members.

Array of Objects

Declaring an array of a class type makes all the objects, calling the default constructor to create each one. Thus, requires the class to have a default constructor.

What if you don't want to have default constructor?

  1. List
    Use list-initialization to initialize each object in the array.
    MyThing s[3] = {{3}, {2}, {4}};
    Every value inside will be the engines for the objects. MyThing only has one member field, so we only provide one value. This is called listing test when we initialize structures by passing in different values.

  2. use STL to reserve some element size

int main() {
	// empty vector and reserve 10 element size
	std::vector<MyThing> s;
	s.reserve(10);
	
	// initialization using emplace_back
	for (int i = 0; i < 10; ++i) s.emplace_back(i);
}