20-CS-122-001 Computer Science II Spring 2012
Inheritance: Examples

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

Next     Source

#include <iostream>
using namespace std;

class A {
   int n;
public:
   A (int n) { this->n = n; }
   int getN () { return n; }
};

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

// Enter at level B: finds no getN() so it goes up 'till it finds a getN()
// at level A.
int main () {
   B b(2,3);
   cout << b.getN() << " " << b.getM() << "\n";
}