Polymorphism  «Prev 

Conversion Constructor - Exercise

Conversion constructors

Objective: Given a class declaration and a function to test the class, identify the conversion constructor and explain what will go wrong when running the test function.

Instructions

Answer the two questions below concerning the ch_stack class and its conversion constructor.
1. Given the following definition of ch_stack class, determine which of the ch_stack constructors is a conversion constructor.
#include <iostream.h>
#include <string.h>
#include <assert.h>
 
//ch_stack implementation with constructor.
class ch_stack {
public:
//the public interface for the ADT ch_stack
   ch_stack();
   ch_stack(int size, const char str[]);
   ch_stack(const char* c);
   explicit ch_stack(int size);
   void  reset() { top = EMPTY; }
   void  push(char c) {
      assert(top != FULL);
      top++;
      s[top] = c;
   }
   char  pop() {
      assert(top!= EMPTY);
      return s[top--];
   }
   char  top_of() {
      assert(top!= EMPTY);
      return s[top];
   }
   int  empty() const
     { return (top == EMPTY); }
   int  full() const
     { return (top == max_len - 1); }
private:
   enum  { EMPTY = -1, FULL = 101 };
   char*  s;    //changed from s[max_len]
   int    max_len;
   int    top;
};

ch_stack::ch_stack(int size):
   max_len(size), top(EMPTY) {
      assert(size > 0);
      s = new char[size];
      assert(s);
   }
   
//default constructor for ch_stack
ch_stack::ch_stack():
  max_len(100), top(EMPTY){
   s = new char[100];
   assert(s);
  }

//domain transfer
ch_stack::ch_stack(int size, const char str[]):
  max_len(size){
   int i;
   assert(size > 0);
   s = new char[size];
   assert(s);
   for (i = 0; i < max_len && str[i] != 0; ++i)
      s[i] = str[i];
   top = --i;
  }

ch_stack::ch_stack(const char* c):
  max_len(strlen(c) + 1) {
   int i;
   assert(max_len > 0);
   s = new char[max_len];
   assert(s != 0);
   for (i = 0; i <= max_len; ++i)
      s[i] = c[i];
   top = --i;
  }

2. Given the following function to test ch_stack, describe what goes wrong here:
void main() {
   ch_stack a = 'a';   //1
   ch_stack b(10);             //2
   ch_stack c = ch_stack(10);  //3
   ch_stack d = 10;         //4
   ch_stack e = "Stack";       //5
   ch_stack f ("ambiguity");   //6
}

Paste your answers below and click the Submit button when you are ready to submit this exercise.