| Same as above - with answers. | Lecture 4 - slide 23 : 24 Program 3 |
// Program indended to illustrate and discuss the rules of polymorphism
// in C++ when we make use of private and public base classes.
// Answers in the next program - or per revealing of trailing comments.
#include <iostream>
#include <string>
using namespace std;
class B {
private:
int b;
public:
B(int b): b(b){}
void Bop(){
cout << "Bop()" << endl;
}
};
class C {
private:
int c;
public:
C(int c): c(c){}
void Cop(){
cout << "Cop()" << endl;
}
};
class D : private B, public C {
private:
int d;
public:
D(int b, int c, int d): B(b), C(c), d(d){}
};
// Reveal...
int f(D &aD){
B *x = new D(1,2,3); // Error: B is a private base
C *y = new D(1,2,3); // OK: C is a public base
D *z = new D(1,2,3); // OK, of course
D *v = new B(1); // Error: Against rules of polymorphism
D *v = new C(1); // Error: Against rules of polymorphism
}
int main(){
D d(1,2,3);
f(d);
}