Calling functions with base class pointers - C++ Class

C++ examples for Class:Inheritance

Description

Calling functions with base class pointers

Demo Code

#include <cstdlib> 
#include <iostream> 
#include <string> 

using namespace std;

class MyBase//from  w w w .  j a v a 2  s .  c  o m
{
public:
  virtual std::string Type()
  {
    return ("MyBase");
  }
};

class MySubBase : public MyBase
{
public:
  std::string Type()
  {
    return ("MySubBase");
  }

};

class MySubBase2 : public MyBase
{
public:
  std::string Type()
  {
    return ("MySubBase2");
  }

};

int main(int argc, char *argv[])
{
  MyBase *thePointer;

  thePointer = new MySubBase;

  if (thePointer == NULL)
  {
    return (-1);
  }

  cout << thePointer->Type() << endl;

  delete thePointer;

  thePointer = new MySubBase2;

  if (thePointer == NULL)
  {
    return (-1);
  }

  cout << thePointer->Type() << endl;

  delete thePointer;

  return 0;
}

Result


Related Tutorials