Consider the following program:
#include "stdio.h"
enum ShapeColor { Red, Green, Blue };
class Shape
{
public:
virtual void draw(ShapeColor color=Red) const = 0;
void PrintColor(ShapeColor c) const {
switch(c) {
case Red: printf("Red\n");
break;
case Green: printf("Green\n");
break;
default: printf("Blue\n");
}
}
};
class Rectangle : public Shape {
public:
void draw(ShapeColor color=Green) const
{
printf("From Rectangle\n");
PrintColor(color);
}
};
class Circle : public Shape {
public:
void draw(ShapeColor color=Green) const {
printf("From Circle\n");
PrintColor(color);
}
};
int main() {
Rectangle r;
Shape *ps = &r;
ps->draw();
Circle c;
ps = &c;
ps->draw();
return 0;
}
Output of above code is as below:
From Rectangle Red From Circle Red
From the output of above program it is clear that for virtual function, actual
function called is resolved at runtime but the default value of the argument is
get resolved in compilation time.
Now this time I leave this on you to analysis and comment on this program its output and default value resolution of virtual function at compile time as well as on run-time.
Waiting for you comment.
No comments:
Post a Comment