Base class pointer to Derived Class object??
-
what is advantage of "Base class pointer to Derived Class object" ? class Base { public: Base(){ cout<<"Constructor: Base"<fun1(); I guess it is having same behaviour. Please let me know wht is advantage of using base class pointer to derived class object? Thanks\ Ash.
-
what is advantage of "Base class pointer to Derived Class object" ? class Base { public: Base(){ cout<<"Constructor: Base"<fun1(); I guess it is having same behaviour. Please let me know wht is advantage of using base class pointer to derived class object? Thanks\ Ash.
It is in fact extremly powerfull and widely used. This is what is called 'polymorphism' (if you google for it, you'll probably find tons of information). The principle is that you declare some virtual function in your base class that can be redefined by a derived class. In this way the derived class can have a different behavior as its parent. And, if you have several different derived classes that inherit from the same base class, they all can be treated as a base class but have different behavior (and, so, they can all be stored in an array for example). If you want a typical example: suppose that you write a program to draw shapes (triangles, squares, circles, ...). What you would do in that case is have a base class CShape that has a virtual method Draw. Each derived class (CSquare, CCircle, CTriangle, ...) will specialize this Draw method for itself. All the shapes, as they are inherited by the same base class can be manipulated exactly the same way (they will be stored in an array, and whenever you need to redraw your drawing, you will call Draw from all the shapes in your array, no matter what shape it really is). This is an extremly important concept in OOP.
Cédric Moonen Software developer
Charting control [v1.2] -
what is advantage of "Base class pointer to Derived Class object" ? class Base { public: Base(){ cout<<"Constructor: Base"<fun1(); I guess it is having same behaviour. Please let me know wht is advantage of using base class pointer to derived class object? Thanks\ Ash.
Try using virtual functions. This gives your base class pointer a behaviour depending on the class where it is derived from.
class CBase
{
public:
virtual void OpenDoor( ) = 0;
};class House: public CBase
{
public:
virtual void OpenDoor( )
{
AfxMessageBox(_T("Open door of house") );
}
};class Car: public CBase
{
public:
virtual void OpenDoor( )
{
AfxMessageBox(_T("Open door of Car") );
}
};CBase* pObject = new House; pObject->OpenDoor( );
-
Try using virtual functions. This gives your base class pointer a behaviour depending on the class where it is derived from.
class CBase
{
public:
virtual void OpenDoor( ) = 0;
};class House: public CBase
{
public:
virtual void OpenDoor( )
{
AfxMessageBox(_T("Open door of house") );
}
};class Car: public CBase
{
public:
virtual void OpenDoor( )
{
AfxMessageBox(_T("Open door of Car") );
}
};CBase* pObject = new House; pObject->OpenDoor( );