In-Class Exercise

Memory Allocation Order


Walkthrough

What is the output of the following program:

 // Memory Allocation Order
 // h21.cpp

 #include <iostream>
 #include <cstring>
 const int MNAME = 30;

 class String {
     char str[MNAME + 1];
   public:
     String() { std::cout << "S"; }
     String(const char* s) {
         std::strncpy(str, s, MNAME);
         str[MNAME] = '\0';
         std::cout << "S(" << str << ')';
     }
     ~String() {
         std::cout << "~S";
     }
 };

 class Base {
     String string;
   public:
     Base() { std::cout << "B"; }
     Base(const char* s) {
         string = String(s);
         std::cout << "B(" << s << ')';
     }
     ~Base() {
         std::cout << "~B";
     }
 };

 class Derived : public Base {
     String string;
   public:
     Derived() { std::cout << "D"; }
     Derived(const char* s, const char* t) : Base(s) { 
         string = String(t);
         std::cout << "D(" << t << ')';
     }
     ~Derived() {
         std::cout << "~D";
     }
 };

 int main() {
     Derived one;
     std::cout << std::endl;
     Derived two("two", "two plus");
     std::cout << std::endl;
 }






  Designed by Chris Szalwinski   Copying From This Site   
Logo
Creative Commons License