Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism: How do you access derived class member functions?

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;
}
like image 907
user3025784 Avatar asked Mar 22 '23 13:03

user3025784


1 Answers

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;
}
like image 95
NicholasM Avatar answered Mar 24 '23 03:03

NicholasM