I see many methods that specify an interface as return value. Is my thought true that it means: my method can return every class type that inherits from that interface? if n
C++ supports a programming technique called polymorphism. That is a derived class can look like a base class to other code that knows nothing about the derived classes. Take a look at his example:
class Shape
{
public:
virtual float Area () const = 0;
};
class Rectangle: public Shape
{
public:
Rectangle (float width, float height)
: m_width(width)
, m_height(height)
{}
virtual float Area () const
{
return m_width * m_height;
}
private:
float m_width;
float m_height;
};
class Circle: public Shape
{
public:
Circle (float radius)
: m_radius(radius)
{}
virtual float Area () const
{
return 3.141592653f*(m_radius*m_radius);
}
private:
float m_radius;
};
Now you can see from this code we've created a base class Shape (our interface) and two derived classes that specialise this class, one a rectangle, another a circle. Now let's create a function that prints out the area of a shape:
void PrintArea (const Shape& shape)
{
printf("Area of shape = %f",shape.Area());
}
This function doesn't care if its a circle of rectangle. Or it cares about is that it's passed a shape and that you can get the area of it, regardless of type.
So this code uses this function:
Rectangle r (5.0f,4.0f);
Circle c (25.0f);
PrintArea(r); // Print the area of the rectangle
PrintArea(c); // Print the area of the circle
Hope this helps.