简体   繁体   中英

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM