Let's say we have a derived class from an abstract base class. A pointer to the abstract base class is declared in the main and allocated to the derived class through "new". How do you access the member functions of the derived class from a pointer to the base class (not from an object of the derived class)?
Example:
#include <iostream>
using namespace std;
class clsStudent
{
public:
virtual void display() = 0;// {cout<<"Student\n";}
};
class clsInternational : public clsStudent
{
public:
void display(){cout<<"International\n";}
void passportNo(){cout<<"Pass\n";}
};
class local : public clsStudent
{
public:
void display(){cout<<"International\n";}
void icNo(){cout<<"IC\n";}
};
int main()
{
clsStudent * s = new clsInternational;
clsStudent * s2 = new local;
s->display();
s->passportNo(); //This won't work
return 0;
}
Cheeky answer: don't. I mean, if you really need to, the answer to your technical question is the dynamic_cast
operation in C++, in order to a conduct a "downcast" (cast from base to derived class).
But stepping back, this is a reasonable use case for a virtual function. Ask yourself, what is the common meaning I want to access?
In this case, we want all students to have an identifying number.
Working source code: http://ideone.com/5E9d5I
class clsStudent
{
public:
virtual void display() = 0;// {cout<<"Student\n";}
virtual void identifyingNumber() = 0;
};
class clsInternational : public clsStudent
{
public:
void display(){cout<<"International\n";}
void identifyingNumber(){cout<<"Pass\n";}
};
class local : public clsStudent
{
public:
void display(){cout<<"Local\n";}
void identifyingNumber(){cout<<"IC\n";}
};
int main()
{
clsStudent * s = new clsInternational;
clsStudent * s2 = new local;
s->display();
s->identifyingNumber();
s2->display();
s2->identifyingNumber();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With