Bruce Eckel's Thinking in C++, 2nd Ed | Contents | Prev | Next |
//: C15:Addv.cpp // Adding virtuals in derivation #include <iostream> using namespace std; class Base { int i; public: Base(int ii) : i(ii) {} virtual int value() const { return i; } }; class Derived : public Base { public: Derived(int ii) : Base(ii) {} int value() const { return Base::value() * 2; } // New virtual function in the Derived class: virtual int shift(int x) const { return Base::value() << x; } }; int main() { Base* B[] = { new Base(7), new Derived(7) }; cout << "B[0]->value() = " << B[0]->value() << endl; cout << "B[1]->value() = " << B[1]->value() << endl; //! cout << "B[1]->shift(3) = " //! << B[1]->shift(3) << endl; // Illegal } ///:~
//: C15:Slice.cpp // Object slicing #include <iostream> using namespace std; class Base { int i; public: Base(int ii = 0) : i(ii) {} virtual int sum() const { return i; } }; class Derived : public Base { int j; public: Derived(int ii = 0, int jj = 0) : Base(ii), j(jj) {} int sum() const { return Base::sum() + j; } }; void call(Base b) { cout << "sum = " << b.sum() << endl; } int main() { Base b(10); Derived d(10, 47); call(b); call(d); } ///:~