Pointer To Derived Classes
Pointer To Derived Classes
Pointers to
objects of a base class are type-compatible with pointers to objects of a derived class. Therefore, a
single pointer (base class pointer) variable can be made to point to objects belonging to different
classes.
However, there is a problem in using base class pointer to access the public members of the derived
class. One such case is when functions name same in base and derived classes. When we call that
function pointer will call function defined in base not of derived class, since pointer is of base class.
Whenever we call a function using base pointer then it start searching that function from base class,
if it finds the function there, then execute that function no matter base pointer points to which
class at that time.
Solutions of above problem: -
1. Declare pointer to derived class.
Declaring two pointers for base and derived classes not provide benefit of inheritance.
Easy method.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
//pointer to derived classes
class abc
{
int a,b;
public:
void get(void)
{
cout<<"enter a,b";
cin>>a>>b;
}
void show(void)
{
cout<<"a="<<a<<"\t"<<"b="<<b<<endl;
}
};
class xyz:public abc
{
int x,y;
public:
void get(void)
{
cout<<"enter x, y";
cin>>x>>y;
}
void show(void)
{
cout<<"x="<<x<<"\t"<<"y="<<y<<endl;
}
};
int main()
{
clrscr();
abc *p; //pointer of base class abc