(10%) Determine whether the following code has syntax erros or
not. If it is correct, predict its output. If it is
incorrect, point out the
mistake(s).
// Function Pointers (P.393)
#include <iostream>
int add(int a, int b)
{ return a + b; }
int sub(int a, int b)
{ return a - b; }
int mul(int a, int b)
{ return a * b; }
int divide(int a, int b)
{ return a / b; }
int main()
{
int (*f)[](int, int) = { add, sub, mul, divide };
for (int i=0; i<4; i++)
{
std::cout << f[i](12, 6) << ' ';
}
return 0;
}
(10%) Determine
whether the following code has syntax erros or not. If it is
correct, predict its output. If it is incorrect, point out the
mistake(s).
// Polymorphism and Virtual Functions
#include <iostream>
using std::cout;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
int area() { return width*height; }
};
class Rectangle: public Polygon {
public:
virtual int area()
{ return width*height; }
};
class Triangle: public Polygon {
public:
virtual int area()
{ return width*height/2; }
};
int main () {
Rectangle rect;
Triangle tri;
Polygon* ppoly1 = ▭
Polygon* ppoly2 = &tri;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';
return 0;
}