Answers/Solutions to Exercises in Chapter 8, Exercise 4
E4: Unfortunately, this
question in the book is not correct. This is what it was intended to be:
Consider the following C++ program. It compiles fine.
class A { public: char string[10]; };//end class A class B : public A { public: int x; };//end class B int main() { B b; printf("%s\n",b.string); return 0; }
We add a constructor to the class A (see below), and all of a sudden, the compiler complains about not having an appropriate default constructor for B and points to the statement B b; in main() as the culprit. Can you explain it?
class A { public: char string[10]; A(char* s) { strcpy(string,s); } };//end class A class B : public A { public: int x; };//end class B int main() { B b; printf("%s\n",b.string); return 0; }
A4: In the first program class A has no explicit
constructors, hence an implicit default constructor is provided by the compiler. Since class B has no explicit constructor defined, the compiler
provides it with an implicit default constructor that calls on the implicit default
constructor for A. And all is fine.
When we add an explicit constructor to the class A,
the implicit default constructor for is A is not created,
and hence the implicit default constructor has nothing to call. During the construction of
b (in B b; statement), the
implicit default constructor tries to call the default constructor for A, but there is none.
Back to Answers/Solutions Index Back to Answers/Solutions for Chapter 8 Index