C++ Tutorial: Classes and Structs

GFreak45

I didnt slap you, i high 5'd your face.
Reaction score
130
Uses: Variables and Functions and Variable References and Pointers

Classes and Structs:

Classes and structs are very powerful tools and are the sole reason for OOP (Object Oriented Programming). Something that I have noticed in my tutoring sessions, is that my students rarely truly realize what a class is. First we will go through the basic motions of creating a class. Then when we have done so, I will thoroughly explain what is happening.

We begin by creating a new empty project, then creating a new header file in our project's headers. Name this header file Pair.h, then put the following lines in the header:
Code:
#ifndef _PAIR_H_
#define _PAIR_H_
 
 
 
#endif

What this does, is it stops the compiler from creating copies of anything inside it, should it be included more than once. Now we start writing our class. It will be called the pair class and it will have 2 private members (variables), x and y.
Code:
#ifndef _PAIR_H_
#define _PAIR_H_
 
class pair
{
private:
    int x, y;
}
 
#endif

Our class will also have the following public methods:
  • pair ();
  • pair (int, int);
  • ~pair ();
  • int getX () const;
  • int getY () const;
  • void setX (int);
  • void setY (int);
Code:
#ifndef _PAIR_H_
#define _PAIR_H_
 
class pair
{
public:
 
        /* Constructors */
 
    pair ();
    //Default Constructor - sets x and y to 0 by default
 
    pair (int, int);
    //Overloaded Constructor
    //@param int - the initial value of x
    //@param int - the initial value of y
 
        /* Destructors */
 
    ~pair ();
    //Default Destructor
 
        /* Accessors */
 
    int getX () const;
    //getX - gets the x member
    //@return int - the value of x
 
    int getY () const;
    //getY - gets the y member
    //@return int - the value of y
 
        /* Mutators */
 
    void setX (int);
    //setX - sets the value of the x member
    //@param int - the new value of the x member
 
    void setY (int);
    //setY - sets the value of the y member
    //@param int - the new value of the y member
 
private:
    int x, y;
}
 
#endif

Now we write the code for each function. Create a source code file called Pair.cpp and #include "Pair.h" on the top (any header file the user creates is accessed via ""s not <>s). By doing this, when you compile the script, the functions defined in the cpp file will not be visible in the header, but their implementation will be available.

Now each function written in the class must be implemented, but before each function's name, we must put pair:: which is the name of the class containing it and the scope resolution operator.
Code:
#include "Pair.h"
 
pair::pair ()
{
    x = 0;
    y = 0;
}
 
pair::pair (int newX, int newY)
{
    x = newX;
    y = newY;
}
 
pair::~pair ()
{
}
 
int pair::getX () const
{
    return x;
}
 
int pair::getY () const
{
    return y;
}
 
void pair::setX (int newX)
{
    x = newX;
}
 
void pair::setY (int newY)
{
    y = newY;
}

Now It is time to explain what was done. A class object is a group of other variables. By declaring an object of class pair, you create 2 new variables of type int, named x and y. Those variables are accessed by <pair variable name>.x or y. ie:
Code:
pair newPair;
newPair.x = 5;
newPair.y = 4;
However, these variables are private, therefore only functions from inside the class can access them directly. Any functions outside of the class (like main) are not capable of accessing private members. Therefore we create accessor and mutator functions to get and set the values of the x and y members publicly. We can do so like this:
Code:
int main ()
{
    pair newPair (35, 50); //calling overloaded constructor
    newPair.setX(25); //x now equals 25, y still equals 50
    for (int x = 0; x < newPair.getY(); x++) //loop uses the value of y
        cout << x << " ";
}

This is what is known as information hiding. It allows a programmer to share the libraries they create without allowing other programmers to copy their work or alter their class in run-time incorrectly.

Calling one of the methods (class functions) of the pair class requires an object of the pair class. The are called like so: object.function(arguments). What this is doing is actually passing the information of the object to the function, so the instant that function is running, using the members with no object referenced defaults to the calling object. That is why we can use x and y without an object specifier. Should we have a variable or argument with the same name as one of the variables, it can also be accessed via this: this->x or this->y.

Constructors and destructors are used for memory allocation and deallocation and they do not have a "type" because they are the function called when the pair class type is created, but they can take arguments. The memory itself is handled by the computer, but each member inside the object must be initialized before it can be used properly. There are 2 ways of doing this:
Code:
pair::pair (int newX, int newY)
{
    x = newX;
    y = newY;
}
or
pair::pair (int newX, int newY) :
    x (newX),
    y (newY)
{
}
As you can see the first one simply sets the values, where as the second has a colon after the arguments, then initialized each value before the scope operators ({}). The difference is the first initialized the variables with no value.
Code:
int x;
int y;
x = newX;
y = newY;
Where as the second initialized the variables with values:
Code:
int x = newX;
int y = newY;
This is the prefered method as classes can contain members of other class types, and the constructor is sometimes an imperitive in determining the actual value of the object.

Destructors are quite like constructors, however, destructors are the function that is called when someone uses the delete operator. This is used to wrap up the object before it is destroyed, any dynamically allocated variables or arrays are to be deleted here. A destructor is signified by the ~ symbol. ie: pair::~pair (); is a destructor for the pair class. Unless you have pointers in a class, there is almost no reason to enter any actions into the destructor.

Passing Classes as Arguments:

Classes can be rather large, and arguments actually are variables of that type, which means that they take up extra memory, whereas we can pass them by reference to avoid extra memory and calling the copy constructor. ie: void someFunction (const string&); where we can apply the const modifier to help us debug if we are not supposed to modify the value of the argument. This is the proper way to pass a class argument. void someFunction (string) is incorrect because this actually creates an entirely new string variable, which means a new member for size, a new array of characters, completely new. This is not that big of a deal with the string class, however, some classes can get into massive ammounts of bytes just for one object, that is why we pass by reference. The exception would be passing pointers, in which case, a reference is not needed as it takes up the same memory as a pointer.

For instance, using a class called employee that has a string member called name:
Code:
employee::employee (const string& newName)
{
    name = newName;
}

To be continued...
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • Ghan Ghan:
    Howdy
  • Ghan Ghan:
    Still lurking
    +3
  • The Helper The Helper:
    I am great and it is fantastic to see you my friend!
    +1
  • The Helper The Helper:
    If you are new to the site please check out the Recipe and Food Forum https://www.thehelper.net/forums/recipes-and-food.220/
  • Monovertex Monovertex:
    How come you're so into recipes lately? Never saw this much interest in this topic in the old days of TH.net
  • Monovertex Monovertex:
    Hmm, how do I change my signature?
  • tom_mai78101 tom_mai78101:
    Signatures can be edit in your account profile. As for the old stuffs, I'm thinking it's because Blizzard is now under Microsoft, and because of Microsoft Xbox going the way it is, it's dreadful.
  • The Helper The Helper:
    I am not big on the recipes I am just promoting them - I use the site as a practice place promoting stuff
    +2
  • Monovertex Monovertex:
    @tom_mai78101 I must be blind. If I go on my profile I don't see any area to edit the signature; If I go to account details (settings) I don't see any signature area either.
  • The Helper The Helper:
    You can get there if you click the bell icon (alerts) and choose preferences from the bottom, signature will be in the menu on the left there https://www.thehelper.net/account/preferences
  • The Helper The Helper:
    I think I need to split the Sci/Tech news forum into 2 one for Science and one for Tech but I am hating all the moving of posts I would have to do
  • The Helper The Helper:
    What is up Old Mountain Shadow?
  • The Helper The Helper:
    Happy Thursday!
    +1
  • Varine Varine:
    Crazy how much 3d printing has come in the last few years. Sad that it's not as easily modifiable though
  • Varine Varine:
    I bought an Ender 3 during the pandemic and tinkered with it all the time. Just bought a Sovol, not as easy. I'm trying to make it use a different nozzle because I have a fuck ton of Volcanos, and they use what is basically a modified volcano that is just a smidge longer, and almost every part on this thing needs to be redone to make it work
  • Varine Varine:
    Luckily I have a 3d printer for that, I guess. But it's ridiculous. The regular volcanos are 21mm, these Sovol versions are about 23.5mm
  • Varine Varine:
    So, 2.5mm longer. But the thing that measures the bed is about 1.5mm above the nozzle, so if I swap it with a volcano then I'm 1mm behind it. So cool, new bracket to swap that, but THEN the fan shroud to direct air at the part is ALSO going to be .5mm to low, and so I need to redo that, but by doing that it is a little bit off where it should be blowing and it's throwing it at the heating block instead of the part, and fuck man
  • Varine Varine:
    I didn't realize they designed this entire thing to NOT be modded. I would have just got a fucking Bambu if I knew that, the whole point was I could fuck with this. And no one else makes shit for Sovol so I have to go through them, and they have... interesting pricing models. So I have a new extruder altogether that I'm taking apart and going to just design a whole new one to use my nozzles. Dumb design.
  • Varine Varine:
    Can't just buy a new heatblock, you need to get a whole hotend - so block, heater cartridge, thermistor, heatbreak, and nozzle. And they put this fucking paste in there so I can't take the thermistor or cartridge out with any ease, that's 30 dollars. Or you can get the whole extrudor with the direct driver AND that heatblock for like 50, but you still can't get any of it to come apart
  • Varine Varine:
    Partsbuilt has individual parts I found but they're expensive. I think I can get bits swapped around and make this work with generic shit though
  • Ghan Ghan:
    Heard Houston got hit pretty bad by storms last night. Hope all is well with TH.
  • The Helper The Helper:
    Power back on finally - all is good here no damage
    +2
  • V-SNES V-SNES:
    Happy Friday!
    +1

      The Helper Discord

      Staff online

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top