Bhan wrote:
b. B *b; D d;
b = &d;
Can I summarize my understanding like this?
Whenever you have the provision to store only base ptr,store the base
ptr that points to dervied object.
When u retrieve it,use static_cast and get the req derived object.Right?
If I understand you correctly, I don't think your statement is
accurate. You shouldn't always refer to a derived class with a base
class pointer just because you can do so. Certainly, one of the main
reasons for using inheritance is to allow abstraction from the
specifics of derived classes, but this is generally done by using
virtual functions to create interfaces for the derived classes to
implement.
Casting back to the derived type from a pointer to the base class is
generally discouraged. If you need to refer to the derived object as
the derived type, not as the more general base type, then generally
speaking you should not be using a pointer to the base class at that
point in the code.
Consider:
// Abstract base class; cannot be instantiated
struct Shape { virtual void Draw() const = 0; }
// A concrete class
struct Square : public Shape
{
Square( float length ) : length_( length ) { /* ... */ }
// Implement the virtual function
void Draw() const { /*...*/ }
// An additional function that applies to Squares
void Rotate( float angle ) { /*...*/ }
private:
const float length_;
};
// Another concrete class
struct Circle : public Shape
{
Circle( float radius ) : radius_( radius ) { /* ... */ }
void Draw() const { /*...*/ }
private:
const float radius_;
};
Now you can use the base classes to refer to the derived classes and no
cast is needed:
void Foo( const Shape& shape )
{
// ...
shape.Draw();
// ...
}
We could pass a Circle or a Square into this function. If we needed to
call Square::Rotate(), we should probably not do so from Foo since
Shape (and its subclass Circle) does not support the Rotate operation.
The design should be altered so that the object we have is guaranteed
to be a Square, e.g.,
void Bar( Square& square )
{
// ...
square.Rotate( 20.5 );
Foo( square );
// ...
}
You might be interested in the FAQ for this group, which as several
sections on inheritance:
http://www.parashift.com/c++-faq-lite/
Cheers! --M