Reputation: 23
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
Upvotes: 0
Views: 967
Reputation: 2450
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.
Upvotes: 1