I am reading the “Learn C the Hard Way” book and found a code snippet there that looks like this (the below is my code, but the structure of the program is the same):
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string name, int age) {;
this->name = name;
this->age = age;
}
~Person() {
}
};
// When whould I do like this?
class Person *Create_person(string name, int age) {
class Person *person = new Person(name, age);
return person;
};
int main() {
Person *person = Create_person("John", 30);
}
Look especially at
class Person *Create_person(string name, int age) {
class Person *person = new Person(name, age);
return person;
};
What kind of function is that? Why would I call it like that and not just Person *person = new Person?
Is it a short form for
class Person {
public:
Person *Create_person(string name, int age){
Person *person = new Person(name, age);
return person;
}
}
?
There is nothing special about that function.
class PersonandPersonare exactly the same type.and
mean the same thing. The function seems pointless anyway, you can just call
new Person(name, age)directly, as you figured already.