20-CS-122-001 Computer Science II Spring 2012
Virtual Functions

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Source

#include <iostream>
using namespace std;

class A {
   int n;
public:
   A (int n) { this->n = n; }
   int getN () { return n; }
   int getM () { return 0; }
   int getP () { return 0; }
   virtual int getN_virtual () { return n; }
   virtual int getM_virtual () { return 0; }
   virtual int getP_virtual () { return 0; }
};

class B : public A {
   int m;
public:
   B (int n, int m) : A(n) { this->m = m; }
   int getM () { return m; }
   int getP () { return 0; }
   int getM_virtual () { return m; }
   int getP_virtual () { return 0; }
};

class C : public B {
   int p;
public:
   C (int n, int m, int p) : B (n, m) { this->p = p; }
   int getP () { return p; }
   int getP_virtual () { return p; }
};

// Enter at level B: finds no getN() so it goes up 'till it finds a getN()
// at level A.
int main () {
   C c(1,2,3);
   cout << c.getN() << " " << c.getM() << " " << c.getP() << "\n";
   A *a = (A *)&c;
   cout << a->getN() << " " 
	<< a->getM() << " " 
	<< a->getP() << "\n";
   cout << a->getN_virtual() << " " 
	<< a->getM_virtual() << " " 
	<< a->getP_virtual() << "\n";
}