Interview Question
Country: United States
This is called Decorator Pattern. It will extend the functionality of existing object at runtime without altering its class layout. Refer wiki for more details.
If you already have a header file of shape.h then you can declare and define a virtual function mGetArea() in the shape.h file itself. It will not impact any functionality of existing library and derived classes also overrides mGetArea() function if necessary.
Shape.h
class cShape
{
/*
* Existing Code
*
*/
//Newly Added Code
protected:
virtual double mGetArea(){
/*
* Implementation the GetArea logic here
*/
return lArea;
}
virtual ~cShape();
};
class cCircle:public cShape
{
double mGetArea(){
/*
* Circle specific GetArea Implementation.
*/
}
};
class cRectangle:public cShape
{
//If you won'n delcare mGetArea function here ,It will access the mGetArea function declared in cShape class.
};
This can be done using Multiple Inheritance I guess. Please check the below code..
Implementations of class's Shape, Circle, Rectangle, Square, etc are available in library
Implementations of class's NewShape, NewCircle, NewRectangle, NewSquare, etc are implemented by us to include getArea() into class Shape and its Derived classes
class Shape
{
//implementation
};
class Circle : public Shape
{
//implementation
};
class Rectangle : public Shape
{
//implementation
};
class Square: public Shape
{
//implementation
};
class NewShape : public Shape
{
public:
virtual double mGetArea() = 0;
}
class NewCirlce : virtual public Shape, virtual public Circle
{
public:
double mGetArea()
{
// implementation
}
}
class NewRectangle : virtual public Shape, virtual public Rectangle
{
public:
double mGetArea()
{
// implementation
}
}
class NewSquare : virtual public shape, virtual public Square
{
public:
double mGetArea()
{
// implementation
}
}
i am not sure if this all is needed. we have the header file with us. why can't we add the new required function GetArea() in the header itself for class shape and the hairarchy ?
- sanjay July 04, 2012MyLibrary.h
----------------
class shape {
//some declarations
protected:
double GetArea() {}; // This is the new addition.
}
The same can be done for the other derived classes as well.
In such case, we will not be breaking the original code which makes use of this library and the new code can make use of the new function which is now a part of the class shape and classes down it.