Advertisement
smatskevich

Virtuals

Feb 20th, 2017
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class A {
  5. public:
  6.     virtual ~A() {}
  7.  
  8.     void f();
  9.     virtual void g() { cout << "A::g" << endl; }
  10.  
  11. private:
  12.     int x;
  13. };
  14.  
  15. void A::f()
  16. {
  17.     cout << "A::f" << endl;
  18. }
  19.  
  20. class B {
  21. public:
  22.     B();
  23.     virtual ~B() {}
  24.     void special() { h(); }
  25.     // Можно сделать чисто виртуальной.
  26.     virtual void h() { cout << "B::h" << endl; }
  27. };
  28.  
  29. B::B()
  30. {
  31.     special();
  32. }
  33.  
  34. class C : public A, public B {
  35. public:
  36.     C();
  37.     virtual ~C() {}
  38.  
  39.     void f() { cout << "C::f" << endl; }
  40.     virtual void g() { cout << "C::g" << endl; }
  41.     virtual void h() { cout << "C::h" << endl; }
  42. };
  43.  
  44. C::C() :
  45.     A(),
  46.     B()
  47. {
  48. }
  49.  
  50. int main()
  51. {
  52.     A* a = new A();
  53.     a->f();
  54.     cout << sizeof( A ) << endl;
  55.     delete a;
  56.  
  57.     C* c2 = new C();
  58.     A* a2 = c2;
  59.     B* b2 = c2;
  60.  
  61.     a2->f();
  62.     b2->h();
  63.  
  64.     delete a2;
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement