Data initialization of a class

6

Is there any class initialization function for C ++?

In Lua, using the classlib library there is the __init function, 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 this:

#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;
}
    
asked by anonymous 20.12.2014 / 01:26

1 answer

3

If I understood what you want to do, you've come close. What you're missing is the builder of the class.

It is a special method that runs before the instance of this class is available, that is, this method constructs the instance. Its use is not mere formality. It gives some assurances that I will not detail now as 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 an odd syntax. It looks like the variable is a function. In a way this could be seen as human gabriel = human("Gabriel Sales", 16); . And this syntax works, too. Try her, too. It is not so used because it gets 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 one.

#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;
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

    
20.12.2014 / 01:37