#include <iostream>
#include <string>
using namespace std;
class Person
{
string name;
public:
Person():name("")
{
cout << "Person default ctor\n";
}
Person(const string& name_in):name(name_in)
{
cout << "Person string ctor: " << name << "\n";
}
~Person()
{
cout << "Person dtor: " << name << "\n";
}
string get_name()
{
return name;
}
};
class Professor:public Person
{
int office;
public:
Professor(const string& name_in, int office_in):Person(name_in), office(office_in)
{
cout << "Professor string ctor: " << get_name() << endl;
}
~Professor()
{
cout << "Professor dtro: " << get_name() << endl;
}
};
int main()
{
Person alice("Alice");
Professor bob("Bob", 10);
return 0;
}
I would assume that the output should be:
Person string ctor: Alice
Person dtor: Alice
Professor string ctor: Bob
Professor dtor: Bob
Since it seems like that should logically follow from the structure of the program. However, the real output is:
Person string ctor: Alice
Person string ctor: Bob
Professor string ctor: Bob
Professor dtor: Bob
Person dtor: Bob
Person dtor: Alice
Can someone explain why this is? What am I not understanding about classes/constructors/destructors that’s making me come up with the wrong output?
First of all,
Professorderives fromPerson. This means that every instance ofProfessorimplicitly contains an instance ofPerson(observe how you’re callingPerson(name_in)inProfessor‘s constructor). This implicit instance will automatically get destroyed when theProfessorobject is being destroyed.This explains why you see:
As to the ordering of the destructor calls, the variables are destroyed in the reverse order of construction. This explains why Bob is destroyed before Alice: