Showing posts with label Constructor. Show all posts
Showing posts with label Constructor. Show all posts

Constructor function overloading in C++

In this tutorial from our Progressive C++ course, we will learn about overloading the constructor functions.

Overload constructors in C++


Many constructors functions

You were hired by a university to create a system to help teachers, especially to work with students' grades.

As you took the Progressive C++ course, you will create a fantastic system, with several classes and objects, hardcore.
But let's take it easy.

Let's create a math class, called Math. For simplicity, she'll do just one operation: average two grades, one student, that's all.

The constructor function will tell the student's average right away.

See how our code looks:

#include <iostream>
using namespace std;

class Math
{
    public:
        Math(double, double);
};


Math::Math(double g1, double g2)
{
    cout<<"Average: "<<(g1+g2)/2<<endl;
}


int main()
{
    Math BruceDickinson(10, 8);

    return 0;
}

The result was 9 right, all nice and cool, and student Bruce Dickinson got a great average.

And speaking of market experience, it is SOOOO common for customers to be asking for changes, new features, etc. Get used to it, it is always requests and complaints.

In that case, the university now wants you to average 3 grades.

Time, it's very simple, just add one more parameter to the list of the constructor function, create the object with the 3 notes and send a bullet, that's it, our code looks like this:

#include <iostream>
using namespace std;

class Math
{
    public:
        Math(double, double, double);
};


Math::Math(double g1, double g2, double g3)
{
    cout<<"Average: "<<(g1+g2+g3)/3<<endl;
}


int main()
{
    Math NeilPeart(10, 9, 10);

    return 0;
}

Everything was fine and Neil Peart had an almost perfect average.

But then your university get in contact and says: look, there are students who will make two disciplines and students who will make three, that is, their system has to calculate the average in both cases.

And now? How will the constructor guess? One hour calculates the average by dividing by 2 and in the other example he divided by 3 because he had one more variable.

Create a class for each case? Of course not, as this is a complication.

Programming was made to make the world easier! This is where builder overloading comes in.


Constructors overloading in C++

C++ has a card up its sleeve: it allows you to create as many constructors as you want. That's right, functions with the same name.
But one thing has to be different: the list of parameters.

Example of a list of different parameters:

  • Math (double, double)
  • Math (double, int)
  • Math (int, double)
  • Math (double, double, double, float, char, int)
  • ...

So, in our example of averages, just create two constructor functions, one that receives two grades and the other that receives three grades:

#include <iostream>
using namespace std;

class Math
{
    public:
        Math(double, double);
        Math(double, double, double);
};

Math::Math(double g1, double g2)
{
    cout<<"Average: "<<(g1+g2)/2<<endl;
}

Math::Math(double g1, double g2, double g3)
{
    cout<<"Average: "<<(g1+g2+g3)/3<<endl;
}


int main()
{
    Math BruceDickinson(10, 8);
    Math NeilPeart(10, 9, 10);

    return 0;
}

See how smart C++ is. When you created the BruceDickinson object, you only passed two arguments, and the object invoked the constructor function that only works with two numbers.

When he created the ana object, he called the other constructor function, the one that works with three values.

That is, C++ calls the correct constructor!
This is the constructor overloading.

Now if you have two constructors with the same parameter list, then there is no way for C++ to guess what function you are trying to invoke, okay?

We will learn a little more about overload when we study a super special class, the string, which does crazy things and wonders with overloading.

Desctructor Function in C++

In this tutorial for our C++ course, we will learn about and use destructors functions.

The Destructor function

In the last tutorial, we talked about the Constructor Function, which exists in every class and is executed whenever an object is instantiated.

Similarly, there is the destructor function, which is performed only when the object is destroyed.

To create a destructor function, just define a function with the same name as the class, with the tilde symbol (~) before it. Let's look at an example, creating a class with constructor and destructor:

#include <iostream>
using namespace std;

class Test
{
    public:
        Test();
        ~Test();
};

Test::Test()
{
    cout << "Constructor" << endl;
}

Test::~Test()
{
    cout << "Destructor" << endl;
}

int main()
{
    Test t;

    return 0;
}

The result will be the two words on the screen. One occurs when creating the object and another occurs when the program ends, and in this case the destructor is invoked.

And just like the constructors, every class has a destructor. Even if you don't define one, there will be a blank pattern, but it will always exist.

They also do not accept any arguments or list of parameters and do not return any information.

What is the Destructor Function for?

Basically, to do things that must be done when an object ceases to exist.
A very common example is to free up memory that has been allocated within an object.

At the moment, we are using silly, small objects, but they are usually giant, with classes with hundreds of variables and dozens of functions. And inside, it is common to dynamically allocate memory, and when that object ceases to exist, it is a good practice to free up all that memory (especially in more critical systems with little memory, such as your watch or your refrigerator's digital system).

Let's suppose you created a system for the bank, and you always want to do a test: if someone accessed the Bank class, instantiating an object. To do this, you define a global scope variable called "spy" with an initial value of 0.

To check if any objects were created, make 'spy = 1' in the destructor, see:

#include <iostream>
using namespace std;

int spy=0;

class Bank
{
    public:
        ~Bank();
};


Bank::~Bank()
{
    spy = 1;
}

int main()
{
    Bank *b;
    b = new Bank;

    delete b;

    cout<<"Spy: " << spy << endl;
    return 0;
}

Let's suppose it is a giant class, with several members, several things happening ... you created an object, used it, did everything correctly and such. Then it is time to delete it, and at that time the destructor function will be executed.

The result will be 'Spy: 1' there in the main(), indicating that someone messed with that Bank class. That is, the destructor, since it is always executed, will execute the operation 'spy = 1'.

Another example of a destructor function is if you create a game and have a character (which is an object) and he simply dies or leaves the game. In your destructor function, you delete the name, take your points, take it out of the teams, take it out of the ranking.

And etc etc, around there people, almost always have things to do when an object ceases to exist, ok?

Constructors Functions in C++ - Object Oriented

In this tutorial, we will learn about a special type of function, the Constructor function, which plays a very important role in object orientation.

The C++ Constructor function

There is a very important function and used in object oriented, it is the construction function.
And it has some unique and special features.

The first is that the name is the same as the class name. That is, if your class is called "MyClass", the constructor function must be called "MyClass()", mandatorily, ok?

Another characteristic of it is that, as soon as we instantiate an object, the constructor function is always automatically invoked!

Finally, one last characteristic, it does not return any value! Do not write void, int, doublet etc., anything in your header and implementation.

Let's see a test of a working construction function? Let's create the "MyClass" class that has only one member, the "MyClass()" function, which will simply display a message, it looks like this:

#include <iostream>
using namespace std;

class MyClass
{
    public:
        MyClass();
};

MyClass::MyClass()
{
    cout << "Progressive C++ Course"<<endl;
}

int main()
{
    MyClass c;

    return 0;
}

Prontinho! Apenas criamos o objeto 'c' e veja o que apareceu na tela:

Constructor functions



Construction function: What is it for?

Ok, we've already seen how to do it, how it works and the result ... but what is it for? Just to show some silly messages on the screen?
Of course not, young man!

As the name says, it serves to 'construct' things, in this case, it builds things automatically. When we create an object, it is interesting that it already does some internal operations immediately, without having to always do everything manually.

This type of constructor, we call it default, because it doesn't take any arguments. However, the most common and useful way to use a constructor function is with a list of parameters, which are information that comes from the outside into the object, and will play an important role inside.


Constructor function: How to use?

For example, let's look at our Rect class, which created rectangles. Remember that we always had to use the setter functions to define the length and width values. How about if the builder did this automatically?

See how it looks:

#include <iostream>
using namespace std;

class Rect
{
    private:
        double length, width;

    public:
        Rect(double, double);
        double getArea();
        double getPerimeter();
};

Rect::Rect(double l, double w)
{
    length = l;
    width = w;
}
double Rect::getArea()
{
    return length * width;
}
double Rect::getPerimeter()
{
    return 2*(length+width);
}

int main()
{
    double len, wid;

    cout<<"Length: ";
    cin >> len;

    cout<<"Width: ";
    cin >> wid;

    Rect r(len, wid);

    cout<<"Area: " << r.getArea() << endl;
    cout<<"Perimeter: " << r.getPerimeter() << endl;

    return 0;
}

Note that in the header of the constructor, we have already specified that it will receive two variables of type double.

In the implementation, we call these variables 'l' and 'w', which will be provided later by the user. And what does our constructor function do? It will set the correct values for 'length' and 'width'.

In main, we ask for the length and width values, and then simply instantiate an object of type Rect, named 'r'. Notice now that in it we send two arguments, which are the two arguments that the constructor function will use!

Ready, internally, inside the object, the constructor has already done everything and the functions getArea() and getPerimeter() can now be used.

A little more about the Constructor Function

Another curiosity about constructors is that they ALWAYS exist! Even if you don't define any, C++ goes there and creates one, empty, that does nothing.

When you do:

  • MyClass c;

It will automatically invoke the constructor, but you don't see anything happening, as you haven't defined any constructors.

Another trick you may need and use, is through pointers, declaring a pointer to an object:

  • MyClass * ptrClass;

When doing this, the constructor method will not be executed, since an object was not created, only a pointer to an object.

Now if you do this next:

  • ptrClass = new MyClass;

Then, the object was instantiated and allocated in memory, and the constructor will be summarily executed.