简体   繁体   中英

C++ Parent Class Default Constructor Called Instead of Parameterized Constructor

I have a parent class called "People" and a child class called "Student". I have set up default and parameterized constructors for both classes along with a cout message in each constructor to display which constructor was called. However, when I create a new Student WITH parameters, such as "Student newStudent(2, "Dave", true);", it calls the default constructor of the PARENT class, but calls the parameterized constructor of the child class. So, the output is: "People default constructor called" and "Student parameterized constructor called". I'm not really sure what I'm doing wrong as the constructors all seem to be set up correctly.

int main():

Student newStudent(2, "Dave", true);

People class (parent):

//Parent Default Constructor
People::People(){
    
    classes = 0;
    name = "";
    honors = false;

    cout << "People default constructor called" << endl;
}

//Parent Parameterized Constructor
People:People(int numClasses, string newName, bool isHonors){
    
    classes = numClasses;
    name = newName;
    honors = isHonors;

    cout << "People parameterized constructor called" << endl;
}

Student class (child):

//Child Default Constructor
Student::Student(){

    classes = 0;
    name = "";
    honors = false;

    cout << "Student default constructor called" << endl;
}

//Child Parameterized Constructor
Student::Student(int numClasses, string newName, bool isHonors){

    classes = numClasses;
    name = newName;
    honors = isHonors;

    cout << "Student parameterized constructor called" << endl;
}

Output:

People default constructor called
Student parameterized constructor called

You need to call your parameterized parent class constructor from your parameterized child class constructor in the initialization list. Something like:

class Parent
{
private:
    string str;
public:
    Parent()
    {
    }
    Parent(string s)
      : str(s)
    {
    }
};

class Child : public Parent
{
public:
    Child(string s)
      : Parent(s)
    {
    }
};

Initialization list are important in constructors. I strongly suggest you look it up and learn about them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM