VD18421
VD18421

Reputation: 295

Calling superclass function inheritance c++

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?

Upvotes: 4

Views: 69

Answers (2)

A.S.H
A.S.H

Reputation: 29332

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.

Upvotes: 3

Sam Varshavchik
Sam Varshavchik

Reputation: 118300

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) {

Upvotes: 0

Related Questions