"Bhan" <> wrote in message
news: oups.com
> Using Ptr of derived class to point to base class and viceversa
> class base
> {
> ...
> }
> class derived : public base
> {
> ...
> }
>
> I want to know any practical scenario when this is used
> a. B b;
> D *p = &b;
You shouldn't do this because the derived class will usually have members
that the base class does not. The derived class pointer will allow you to
try to access members of the derived class than don't exist in the base
class object, with possibly disastrous consequences.
> b. B *b;
> D d;
> b = &d;
This is safe and very useful, though it rarely occurs in the context that
you have shown. It occurs in two main contexts.
1. Containers of pointers. The container (an array or vector or whatever)
can usually only store pointers of a single type. If you want it to point to
both base and derived class objects, then you store base pointers and assign
to those base pointers the addresses of both base and derived class objects.
You can then iterate over all the members in the container, calling the same
function for each. If the function is virtual, then you can get a different
function for the pointers pointing to the derived class objects as compared
to the pointers pointing to the base class objects (this is known as
run-time polymorphism). For non-virtual functions, you get the same function
in both cases, but this is OK since the function is a member of both the
base and the derived class (with public inheritance, any public function in
the base class becomes a public function in the derived class).
2. Functions that take pointer arguments. Given, say:
Base b;
Derived d;
void foo(Base *ptr)
{
ptr->MemberFunction();
}
you can call this function using the address of either a base class or a
derived class object:
foo(&b);
foo(&d);
The effect of the first is:
ptr = &b;
ptr->MemberFunction();
The effect of the second is:
ptr = &d;
ptr->MemberFunction();
--
John Carson
|