ex7-12.cpp - Example 7-12 Virtual Functions (3)

// File: ex7-12.cpp

// This example shows that "vitualness" is passed down to derived classes
// even if the immediate "parent" class does not name a function as virtual.
// It also illustrates polymorphism implemented through references instead
// of pointers to base objects.

#include <iostream>
using namespace std;

class person
{
  protected:
	 int data;
  public:
	 virtual char * who_am_i() { return "person"; }
	 char * non_virtual_who_am_i() { return "non_virtual person"; }
};

class child : public person
{
  public:
	 char * who_am_i() { return "child"; }
	 char * non_virtual_who_am_i() { return "non_virtual child"; }
};
class grand_child : public child
{
  public:
	 char * who_am_i() { return "grand_child"; }
	 char * non_virtual_who_am_i() { return "non_virtual grand_child"; }
};

void identify_yourself(person& p)
{
  cout << "I am a " << (p.who_am_i()) << endl;
  cout << "I am a " << (p.non_virtual_who_am_i()) << endl;
}

int main()
{
  person P;
  child C;
  grand_child G;
  person* pp;
  pp = &P;
  cout << (pp->who_am_i()) << endl;
  cout << (pp->non_virtual_who_am_i()) << endl;
  pp = &C;
  cout << (pp->who_am_i()) << endl;
  cout << (pp->non_virtual_who_am_i()) << endl;
  pp = &G;
  cout << (pp->who_am_i()) << endl;
  cout << (pp->non_virtual_who_am_i()) << endl;
  cout << "sizeof(int) = " << sizeof(int) << endl;
  cout << "sizeof(person) = " << sizeof(person) << endl;
  cout << "sizeof(child) = " << sizeof(child) << endl;
  cout << "sizeof(grand_child) = " << sizeof(grand_child) << endl;
  identify_yourself(P);
  identify_yourself(C);
  identify_yourself(G);

  return 0;
}



CIS27: Programming in C++    Instructor: Joe Bentley