Object Oriented Programming 2
Object Oriented Programming 2
1. Direct solution:
Student::SetAge() or Salaried::SetAge()
2. Virtual inheritance
Solution (virtual inheritance)
class A {
public: void Foo() {}
}
D d;
d.Foo(); // no longer ambiguous
Virtual Inheritance
●Virtual inheritance is a C++ technique that
ensures that only one copy of common
base class's member variables are
inherited by second-level
derivatives (a.k.a. grandchild derived
classes)
Example
class PoweredDevice
{
public:
PoweredDevice(int nPower)
{
cout << "PoweredDevice: " <<
nPower << endl;
}
};
class Scanner: public PoweredDevice {
public:
Scanner(int nScanner, int nPower) :
PoweredDevice(nPower)
{
cout << "Scanner: " <<
nScanner << endl;
}
};
};
Example
int main()
{
Copier cCopier(1, 2, 3);
}
private:
float height;
float width;
int xpos;
int ypos;
public:
rectangle(float, float); // constructor
void draw(); // draw member function
void posn(int, int); // position member function
void move(int, int); // move member function
float get_height(); // access function
void set_height(float); // access function
};
void set_value(rectangle &rc, float h)
{
rc.height = h;
}
void main()
{
rectangle rc(1.0, 3.0);
set_value(rc, 10.0);
}
Example