Introduction to Classes#
reading
C++ classes from Wikipedia
Classes are a fundamental part of the object-oriented programming paradigm. A class is an object that holds both data and functions that know how to operate on the data.
Tip
In C++, both struct and class create a class, with the difference being
whether the data is publicly accessible by default.
We’ll start by making a class that describes a circle:
#include <iostream>
#include <numbers>
#include <format>
struct Circle {
// member data
double radius{};
// constructor
Circle(double r) {
radius = r;
}
// member functions
double circumference() {
return 2.0 * std::numbers::pi * radius;
}
double area() {
return std::numbers::pi * radius * radius;
}
};
int main() {
Circle c(3.0);
std::cout << std::format("circle with radius {:6.3f} has circumference {:6.3f} and area {:6.3f}\n",
c.radius, c.circumference(), c.area());
}
Let’s understand the syntax:
We use
structjust like we did before, but now in addition to data, there are functions inside the{ }that define thestruct.We start with the member data. In this class, there is only piece of member data,
radius—the radius of our circle.We have one special function here, the constructor—it has the same name as the class,
Circle. This is what is called when we create an instance of our class, e.g.,Circle c(2.0);
calls our
Circle(double r)function in our classCircle.We have two member functions:
circumference()will return the circumference of the circlearea()will return the area of the circle
Notice that we don’t need to pass the radius into this functions. Since they are members of the class, they will use the member data
radiusdirectly. We invoke these on our instance of the class, e.g.,auto C = c.circumference();
This is the power of classes—the functions work directly on the data that is a member of the class.