Exercise 8 from Thinking in C++ Vol 1 reads (Chapter 7):
Modify SuperVar so that there are #ifdefs around all the vartype code as described in the section on enum. Make vartype a regular and public enumeration (with no instance) and modify print( ) so that it requires a vartype argument to tell it what to do.
Below I include the original code, followed by the program amended by myself. I cannot workout why, in the amended program, only
A.print('d');
seems to be executed properly. It appears that
B.print(12322);
C.print(1.44F);
are not processed by SuperVar::print
Your comments will be gratefully received.
//: C07:SuperVar.cpp
// A super-variable
#include <iostream>
using namespace std;
class SuperVar {
enum {
character,
integer,
floating_point
} vartype; // Define one
union { // Anonymous union
char c;
int i;
float f;
};
public:
SuperVar(char ch);
SuperVar(int ii);
SuperVar(float ff);
void print();
};
SuperVar::SuperVar(char ch) {
vartype = character;
c = ch;
}
SuperVar::SuperVar(int ii) {
vartype = integer;
i = ii;
}
SuperVar::SuperVar(float ff) {
vartype = floating_point;
f = ff;
}
void SuperVar::print() {
switch (vartype) {
case character:
cout << "character: " << c << endl;
break;
case integer:
cout << "integer: " << i << endl;
break;
case floating_point:
cout << "float: " << f << endl;
break;
}
}
The SuperVar::print function takes an enum as the arg. It doesn't take float, int, char, or any other type. You are calling print with the wrong kind of values. Honestly, I am surprised that your amended program compiles. I didn't think that an enum could be implicitly constructed like that during a function call.
Many thanks for the response. I have run various amended versions of the original program in order to attempt to complete the exercises in the book. The results obtaining are the same as first suggested. Am I correct in concluding that the question cannot be done?
The process has been useful because, hopefully, I understand better how enum and union work. However, I have two remaining questions:
1 . Enum VarType and union do not appear to be linked by a command. Do they always go together? In the original code it is evident that the information they provide is complementary. The examples I found in the Internet are not explicit.
2 . What is the effect of making one public and the other private?