C ++ inheritance superclass function call

In my C ++ file, when I run visual studio, my result is not the one that I thought it was not me, I do not know where I messed up. Basically, I have a class Personand Student, and the student class is inherited from the Person class, and when the student object obj is created, it calls the Person class to initialize the shared variables.

class Person {
public:
    Person() {

    }
    Person(string _name, int _age) {
        name = _name;
        age = _age;
    }

    void say_stuff() {
        cout << "I am a person. " << name << age << endl;
    }

private:
    string name;
    int age;
};

class Student : public Person {
public:
    Student(string _name, int _age, int _id, string _school) {
        Person(_name, _age);
        id = _id;
        school = _school;
    }

private:
    string name;
    int age;
    int id;
    string school;

};



int main() {


    Student s1("john", 20, 123, "AAAA");
    s1.say_stuff();

    system("pause");
    return 0;

}

My conclusion. I am a person. -858993460 Why is this?

+4
source share
2 answers

The way you call the constructor of a superclass is wrong. So you should do this:

Student(string _name, int _age, int _id, string _school) : Person(_name, _age) {
   id = _id;
    school = _school;
}

: Person(_name, _age); , , Person. , "" Person, .

+3

Student , . :

Student(string _name, int _age, int _id, string _school)
        : Person(_name, _age) {
0

Source: https://habr.com/ru/post/1669772/


All Articles