/* 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?
There are only two objects being constructed, the 3 couts you see in the constructor is because of the fact that when you create a derived class object the base class constructor is called. As a side note, you need to declare class a destructor as virtual.
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 constructor b(char c1, char c2) : a(c1) and you are telling it to also use class a constructor which means that you have already have called 2 constructors in this case. and the last constructor is for this object a var2('o'); in this case you are using the constructor in class a. so in total you have used 2 constructors in class a and 1 constructor in class 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With