Not that I have a problem but I found weird following fact.
/* Class Shape */
class Shape
{
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
/* Class Triangle */
class Triangle: public Shape
{
public:
Triangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
int main( )
{
Shape *shape;
Triangle tri(10,7);
shape = &tri;
(*shape).area();
return 0;
}
What above will be print is: "Parent class area :".
So it seems the compiler does not check the pointer contents? And calls method only based on pointer type? Otherwise it would have seen that *shape
is a Triangle
object and would have called Triangle version of area isn't it?
ps. I know you can use virtual functions to make it work the way I describe but that't now what I was interested in, just I found this behaviour little bit weird, maybe I am missing something.