Showing posts with label OOP. Show all posts
Showing posts with label OOP. 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?

How to create a Class and Objects in C++

Now that we have a good idea of what the Object-Orientada programming paradigm is, as well as the Class and Object concepts (in a more abstract way), let's get our hands dirty and make code! Create such classes and real objects.

How to create a Class in C ++

Initially, the concept of class encoding is very reminiscent of structs. In this case, we will use the keyword class to create a Class, as follows:

#include <iostream>
using namespace std;

class MyClass
{
    //Informations
    //about your
    //Class
};

int main()
{
    return 0;
}

That is, we write class, choose a name for our class, open keys and put all the information about it inside. Don't forget to put a semicolon at the end of the class scope!

Ready, the MyClass class was created! Also note that it is not within the main() function, but at the same level as it.

Defining members of a Class: Variables and Functions

Shall we create a real class? We will create a class that will create squares. Our class is called Square.

What is an important data of a square? Hey, its side. Soon, it will have a variable that stores its side.

What other important 'thing' in a square? Its area. Let's create a function that calculates the area of that square. Our class looks like this:

#include <iostream>
using namespace std;

class Square
{
    double side;
    double area();
};

double Square::area()
{
    return side*side;
}

int main()
{
    return 0;
}

There, there is the declaration of the variable 'side' as well as the header of the area() function. And this function, where are we going to declare? It was declared after the scope of the class.

So far, in our course, if we wanted to declare an area() function in our programs, we would do:

double area()
{
     return side * side;
}

And this function is visible and accessible to our entire program, correct?

What if we want to create a function that is a Class and should be visible and accessible only by that class?
We do:

double Square::area()
{
    return side * side;
}

Understood? Put "ClassName::" before the function name, that says that function is of the ClassName class, and only it has access and can use that function!

How to create and instantiate objects in C++

Ok, our class is cute and done! Now let's create objects from it!
If you want to create information of the entire type, you do:

int num;
int age;
int ID;

If you want to create string information, you do:
string name;
string address;

And so on. If you want to create information like 'MyClass', you do:

MyClass example;

For example, to create an object of class Square, you would do:

Square q1;
Square square;

Let's call our object 'q', we create it like this:

#include <iostream>
using namespace std;

class Square
{
    double side;
    double area();
};

double Square::area()
{
    return side*side;
}

int main()
{
    Square q;

    return 0;
}

Ready. Now there is a real square, called Square, which has 'side' and 'area()' members. Nice, right?

When we create an object, we say that we are instantiating an object q of class Square. It is a new 'instance' of the class.

You can even create another object, or millions, just give them different names: q1, q2, ..., q2112 ... each one will have its characteristics: its 'side' values and its areas. Although they are of the same Square 'type' (that is, they all have side and area() in common), each has its specific values.

It's just like us, people ... everyone has a name, heart, lung capacity, age ... but each has its own specific values (specific name, specific age, specific physical condition). Now you understand better the concept of Class and Object, in C++?

In the next tutorial we will learn how to access, change and use these members of the Square class.

What are Classes and Objects in C++

In this tutorial of our C++ course, we will learn in a very colloquial and simple way, what classes and objects are, the basis of object-oriented programming.

What is a Class

Class is nothing more than a blueprint, a mold, a diagram.
For example, let's imagine a class Car.

This class will describe all the details of this car: its size, number of doors, engine power, whether it is manual or automatic, whether it has a sunroof or not, its utilities, etc.

That's basically it, it's a 'form', which explains what the ... objects are like.
To make a car, we need the details of the Car class to create a car. This car is going to be an object.
Yes, to explain class, we have to talk about object ...

What is an Object

... and to talk about Object, we need to talk about Class. It is not possible to separate or explain one of the two things well, something is 'vague', and I hate these technical and vague explanations.

Everything you know is an object. You are an object, you live in an object, you eat objects, you move around objects, you are accessing this page / booklet through an object, in fact, this course is an object.

Everything is an object.

Understand object as the real, day-to-day things that actually exist. And class, like something abstract.

Class and its Objects

A good way to explain something is through real examples. So come on.

Let's say you completed the Progressive C++ course and became a hell of a C++ programmer, with an excellent salary, and decided to buy a car.

You won't come to the dealership and say, "Hey, man, I want a car".
And the salesman won't say, "Okay, here's a car".
Nor will you answer, "Thanks, I have a car now"

When you go to buy a car, you will want a Civic, a Camry, a Corolla or a BMW (if you are a C++ programmer). That is, you will buy something specific. That specific car is an object. An object of the class Car.

The class Car will say: "These objects have x doors, such a engine, transmission, such power, such color ...", that is, the common characteristics that all cars have. All cars have doors and engines, for example.

A Volkswagen Beetle has two doors and a weak engine. Your Audi has 4 doors and a huge power. But both have a certain number of ports and an exact power value.

In other words, a Beetle, a BMW, a Mercedes ... they are all objects of the Car class.

Got it?

Class and objects in C++


Attributes and Functions of Classes and Objects

Let's go to one more example. You don't know or deal with a 'human'. You deal with your father, your mother, your friends ... that is, 'specific' humans.
Let's create the Human class. What are the characteristics of a human? Hey, he has a name, age, height, weight, heart, lung, etc. etc.

We call these attributes details, their details, their information.

This class will also 'do' some things, such as: breathing, beating the heart, walking, sleeping ... that is, the Human class, in addition to having characteristics (values, numbers), it will also have some actions ... these actions are functions.

Specific functions that only exist in the Human class. After all, it does not have a Breathe() function in the Car class, nor does it have a Shifting() function in the Human class.

That is, each Class has its characteristics (attributes) and specific actions that occur there (functions). This is what defines a class: attributes and functions.

The cool thing about object-oriented programming is that the functions of the Car can only act on objects of the Car type, and the actions of the Human class will only be able to act on objects of the Human class.

Instantiate (create) objects from a Class

When you are going to create something, that something was created from a class. That is, we say that the object was instantiated from a class.

For example, suppose you were hired by a company to work in the HR industry. At first, you will create a class called Employee.

What are the characteristics of an Employee? Hey, he has a name, position, salary, identification number ...

When someone new is hired, you need to create a specific object for that new employee. We say that you will instantiate an object of the Employee class.

This object has a name "Neil Peart", age (32), salary ($ 10,000.00/month- after all, it is a C++ programmer), identification number (2112) ...

That is, objects are real things, based on abstract stuff (classes).

From the next tutorial, we will really learn how to program classes, how to instantiate objects, how to define their characteristics and actions.

Object Oriented in C++: Introduction

 Before going into detail about a new programming paradigm (object oriented), let's understand a little what we were going to do and what we are going to do differently.


Functional Programming

So far, we have only used one programming style: functional, also called procedural. As the name says, it is a method that uses procedures, or as we call it: functions.

Basically, it is a script, a routine of procedures and commands. In other words, we only use variables and functions. Let's take an example.

Suppose you want to calculate the arithmetic average of two numbers, in C++. Necessarily, you will have to have two variables to store the values and an average calculation. There, there is a 'script' of what should be done.

What you can do differently, is to put the average in a function, so that it can be invoked indefinitely:

#include <iostream>
using namespace std;

float average(float num1, float num2)
{
    return (num1+num2)/2;
}

int main()
{
    float num1, num2;

    cout<<"Number 1: ";
    cin >> num1;

    cout<<"Number 2: ";
    cin >> num2;

    cout<<"Average: "<< average(num1,num2) << endl;

    return 0;
}

See how this program is just a procedure, it starts running from the beginning of main() and goes to the end of it. Always. Everything we did was always like this. It has a beginning (usually variable declaration), a middle (calling functions to do various things) and an end (showing results).

The purpose of functional programming is to create functions that do things. It may seem simple and fool right? But incredible things were done using this. The Linux Kernel, for example, does not use C++, only C, that is, it has no object oriented, only procedural programming.

Over the years and decades, software has become more and more and more and more, and a little more, complex. And some problems were emerging.


Oriented Object Programming

So far, in our programs, any function could work on any data. This over time became a security issue. It would be ideal if certain functions could act only on some data.

For example, in functional programming, functions that work with a company's Treasury data could work with any data, such as that of Employees. But it would be better if the treasury had its own functions and to work with employee data, they had their own functions as well. And for the sake of security, none could touch the things of others.

Another problem: you assign a function to receive an integer. Someone accidentally uses this function and sends a float. If you do this test, it will give an error, the wrong answer will come out and it can even simply close the program by running. Can you imagine 'closing' the program of an airplane, in mid-flight? It's not cool, right?

Hence the blessed and beautiful OOP: Object Oriented Programming. It solves these problems, and in an incredibly simple and easy way. Its secret is: it starts working with something called an object.

Each object will have its own variables and only a few functions can see it act on it.

If you have a Sound object in your game, it will have specific variables, characteristics and functions acting on it. Character type objects will have specific variables, characteristics and functions for them. A function that affects Sound cannot act on a Character type object. And, wow, that avoids many bugs and potential problems.

That of each object having its data and procedures, is the so-called encapsulation, the basis of the OOP logic. It is as if there is a specific code for each 'thing'. A function only sees data for that 'thing' and can only act on that 'thing'. You can even hide information, say clearly: 'Hey, this variable here, which stores the password, can only be seen here inside the server, it is inaccessible to users outside'. And that brings incredible security.

If you are developing a game in C++ and use object orientation, you will create data and procedures that will only act and make sense in the Logic part. It will create information and functions that will only be visible and will only act on Graphics, you will create specific things for the Scenario (which are not even visible outside this scope). You encapsulate, you divide, you organize things ... are you getting the idea of OOP?

It is no longer that mess of functions and variables that everyone can see and use. A declared variable should generally only be used by the X() function. But the Y() function can indeed see and act on this variable, this is an error, a problem, and it would be interesting if this were naturally impossible, if the language itself made this separation. And it is this separation that Object Oriented does.

If you make a Web system, you want only a few functions to be available to users, such as the function Display(), which will show the grades of an Distance Education student. But if you used functional programming, the evil student can create code that calls the ChangeGrade() function, to change your grades, to hack the system. Well, he may well "guess" the name of the functions, and he will get it right...

With object-oriented programming, we can make it very clear: "Hey system, only this function and these variables can be accessed by students". When he tries to invade the system, calling other functions that are not part of that 'object' (his grades, for example), he will be summarily blocked.

This object orientation is cool, right? But let's stop talking and go to the next tutorial and start learning how to use this awesome thing for good.

Study resources

Programming Paradigm
Functional Programming