Key to Quiz 7 [8 questions and a survey, 22 points, 20+5 min] WRITE YOUR MAJOR, NAME and ID4: Q1. Suppose we do not want function fn to take any parameter type other than B. Find out a mistake in the main function. How to make sure that mistake is prevented by the compiler. [2] 1 // explicit: 2 #include <iostream> 3 using namespace std; 4 5 class A {}; 6 class B { 7 public: 8 explicit B (const A& x) {} // REMOVE IN QUESTION: key word explicit before 9 constructor 10 B& operator= (const A& x) {return *this;} 11 operator A() {return A();} 12 }; 13 14 void fn (B x) {} 15 int main () { 16 A foo; 17 B bar (foo); 18 bar = foo; 19 foo = bar; 20 21 fn (foo); // REMOVE this comment IN QUESTION: not allowed for explicit ctor. 22 fn (bar); return 0; } ANS: line 20 function call should not succeed. Add “explicit” before the constructor on line 8. Q2. In the following code add the blank line (17) to type-cast variable d to a pointer of padd of type Addition. [2] 1 // class type-casting 2 #include <iostream> 3 using namespace std; 4 5 class Dummy { 6 double i,j;}; 7 8 class Addition { 9 int x,y; 10 public: 11 Addition (int a, int b) { x=a; y=b; } 12 int result() { return x+y;} }; 13 14 int main () { 15 Dummy d; 16 Addition * padd; 17 padd = (Addition*) &d; // REMOVE IN QUESTION 18 cout << padd->result(); 19 return 0; }
Key to Quiz 7 [8 questions and a survey, 22 points, 20+5 min] WRITE YOUR MAJOR, NAME and ID4: Q1. Suppose we do not want function fn to take any parameter type other than B. Find out a mistake in the main function. How to make sure that mistake is prevented by the compiler. [2] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // explicit: #include <iostream> using namespace std; class A {}; class B { public: explicit B (const A& x) {} // REMOVE IN QUESTION: key word explicit before constructor B& operator= (const A& x) {return *this;} operator A() {return A();} }; void fn (B x) {} int main () { A foo; B bar (foo); bar = foo; foo = bar; fn (foo); // REMOVE this comment IN QUESTION: not allowed for explicit ctor. fn (bar); return 0; } ANS: line 20 function call should not succeed. Add “explicit” before the constructor on line 8. Q2. In the following code add the blank line (17) to type-cast variable d to a pointer of padd of type Addition. [2] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // class type-casting #include <iostream> using namespace std; class Dummy { double i,j;}; class Addition { int x,y; public: Addition (int a, int b) { x=a; y=b; } int result() { return x+y;} }; int main () { Dummy d; Addition * padd; padd = (Addition*) &d; // REMOVE IN QUESTION cout << padd->result(); return 0; }