/* Problem 50 */
#include <iostream>
using namespace std;
class a {
char ach;
public:
a(char c) { ach = c - 1; }
~a(); // defined below
virtual void out(ostream &os) {
if ('m' < ach)
os << ach << char(ach+7) << char(ach+6) << ' ';
else
os << ach << ach << ach;
}
};
class b: public a {
char bach;
public:
b(char c1, char c2) : a(c1) { bach = c2-1; }
void out(ostream &os) {
a::out(os);
os << ' ' << bach << char(bach + 11);
}
};
ostream &operator<<(ostream &os, a &x) {
x.out(os);
return os;
}
a::~a() {
cout << *this; // calls above operator
}
int main() {
b var1('n', 'e');
a var2('o');
cout << "Homer says: " << var1 << '\n';
return 0;
}
I’m confuse why only two object being destruct while there are three object being construct
I also have put cout on each of the construct on the base_class and the derived_class to see how many were construct and I was right about the number of constructed object, but I was wrong when I did the destruct.
If anyone could please point me out why the last destruct didn’t apply to the first object that being create?
when you are creating the first object in the main
b var1('n', 'e');which means that this object will be constructed by class b constructorb(char c1, char c2) : a(c1)and you are telling it to also useclass aconstructor which means that you have already have called 2 constructors in this case. and the last constructor is for this objecta var2('o');in this case you are using the constructor inclass a. so in total you have used 2 constructors inclass aand 1 constructor inclass b.you have 2 objects and the reason why you see 2 objects being destructed is because you have a
~a()but you don’t have~b().hope this will help