Initialization of data of a class

Asked

Viewed 272 times

6

Is there a class initialization function for C++?

In Lua, using the library classlib there is the function __init, and in Python as well. EX:

require "classlib"

Human = class();

function Human:__init(name, age)
  self.name = name
  self.age = age
end

gabriel = Human("Gabriel", 16)

print(gabriel.name, gabriel.age)

In C++ I had to do so:

#include <iostream>
#include <string.h>
using namespace std;
class human {
    public:
        string name;
        int age;
        void SET(string, int);
};

    void human::SET(string name, int age){
        this->name = name;
        this->age = age;
    }
int main (){
    human gabriel;
    gabriel.SET("Gabriel Sales", 16);
    cout << gabriel.name;
    return 0;
}

1 answer

3


If I understood what you want to do, you came close. What you lack to know is the builder class.

It is a special method that is executed before the instance of this class is available, i.e., it is this method that builds the instance. Its use is not mere formality. It gives some assurances that I will not go into now since you are starting.

Note that the constructor has the same class name and does not have a return type, not even void.

Note also that the initializer has a strange syntax. It seems that the variable is a function. In a certain way this could be seen as if it were human gabriel = human("Gabriel Sales", 16);. And this syntax works too. Try it too. It’s not used as much because it’s too long and redundant.

There are other ways to boot especially in C++11 which is the latest version but this is the most used.

#include <iostream>
#include <string.h>
using namespace std;

class human {
    public:
        string name;
        int age;
        human(string, int);
};

human::human(string name, int age) {
    this->name = name;
    this->age = age;
}

int main() {
    human gabriel("Gabriel Sales", 16);
    cout << gabriel.name;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Exactly that.

  • @Bigown Only in C++ o this is a pointer and has to be treated like this -> ?

  • @axell13 no, if you have any specific question, you want comparison with some language, ask a question that I try to answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.