Back to notes -- Keyboard shortcut: 'u'        next -- Keyboard shortcut: 'n'  Slide program -- Keyboard shortcut: 't'    Virtual versus non-virtual functions in an AB class hierarchy.Lecture 4 - slide 5 : 24
Program 1
// Class B inherits from A. We activate virtual (vf) and non-virtual (f) functions
// on a parameter passed by value, by a pointer, and by reference.

#include <iostream>
#include <string>

using namespace std;

class A {
private:
   double a;
public:
  virtual void vf(double d){
    cout << "virtual vf in A" << endl;
  }

  void f(double d){
    cout << "f in A" << endl;
  }
};

class B : public A {
private:
  double b;
public:
  void vf(double d){
    cout << "virtual vf in B" << endl;
  }

  void f(double d){
    cout << "f in B" << endl;
  }
};

int f1(A a){
  a.vf(1.0);       // virtual vf in A. Why?  Because a is sliced during parameter passing.
  a.f(2.0);        // f in A
  cout << endl;
}

int f2(A *ap){
  ap->vf(3.0);     // virtual vf in B
  ap->A::vf(3.0);  // vf in A
  ap->f(4.0);      // f in A
  cout << endl;
}

int f3(A &ar){
  ar.vf(5.0);      // virtual vf in B
  ar.A::vf(3.0);   // vf in A
  ar.f(6.0);       // f in A
  cout << endl;
}

int main(){
  B  b1;
             // We pass b1 to f1, f2 and f3
  f1(b1);    //    ... by value             (a copy of b1 is passed)
  f2(&b1);   //    ... a pointer by value   (a pointer to b1 is passed)
  f3(b1);    //    ... by C++ reference     (b1 as such is passed)
}