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.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top