Welcome back to the Digilent Blog! Today, we’re going to learn about classes in C++!
C++ is an object-oriented programming (OOP) language. Here is a great link to the three pillars of OOP — encapsulation, inheritance, and polymorphism.
Classes are the bases of an oriented programming language. We won’t go over all three pillars of OOP specifically today, but if your interested in polymorphism, check out my previous post,”The Brief Intro to C++”, where we learn about function overloading. Classes use encapsulation to contain information and relevant functions.
A class looks similar to a struct, and in a sense, they are pretty close — but there are important differences. We need to create our constructor and destructor, which initialize and destroy the class, respectively. When you look at the picture above, you can see that there is a label that says “public:” and “private:”. Public means that you can access this anywhere that the class has been declared. Private means that only the class has access to these variables (or functions).
For this class, all our variables are going to be private.
If all the variables in our class are set to private, how can we access and manipulate them? Well, that’s where the getter and setter functions come in. Setter functions allow us to “set” the variable that is called. Getters return (or get) the variable that we want.
If you check out the getter and setter code, it’s lengthy but fairly simple! This is great, but doesn’t really do much. Since our class is titled “Rectangle”, we’re going to make functions that calculate volume and surface area. These functions aren’t too complicated, but they are good examples.
This is just a brief intro to classes, but I hope you can begin to see how important these are in OOP!