4

In my C++ file, when I run it visual studio, my output is not what I thought it was be an I don't know where I messed up. Basically I have a Person and a Student class, and the student class inherits from the Person class, and when the student obj is created, it calls the Person class to initialize common 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 output is I am a person. -858993460 Why is this?

2 Answers 2

3

The way you invoke the constructor of the super class is wrong. This is how you should do it:

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

Note that, When you put Person(_name, _age); inside the body, it has no effect but to construct a temporary Person object. On the other hand, the correct way above references the "embedded" Person to be constructed with these parameters.

Sign up to request clarification or add additional context in comments.

Comments

0

Your Student constructor's syntax is wrong, for constructing it's superclass. It should be:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.