Search code examples
c++dynamic-binding

Dynamic binding and static


I guess i am having some trouble in understanding dynamic bynding.

Suppose we are having 2 classes:

class a1{ //..
virtual void print() const;
};

class a2:a1{ //...
void print() const override;
};

Why is the following true:

a2 item_son;
a1 &item_father = item_son;
item_father->print();

the print called is the one of the son.


Solution

  • Actually, the OP did realize the meaning of virtual overloading vs. non-virtual overloading of functions. However, I got my sample running, hence, I'd like to publish it:

    #include <iostream>
    
    class A1 {
      public:
      virtual void print() const
      {
        std::cout << "A1::print() called." << std::endl;
      }
    };
    
    class A2: public A1 {
      public:
      void print() const override
      {
        std::cout << "A2::print() called." << std::endl;
      }
    };
    
    class B1 {
      public:
      void print() const
      {
        std::cout << "B1::print() called." << std::endl;
      }
    };
    
    class B2: public B1 {
      public:
      void print() const
      {
        std::cout << "B2::print() called." << std::endl;
      }
    };
    
    using namespace std;
    
    int main(void)
    {
      A2 a2;
      cout << "Calling a2.print(): ";
      a2.print();
      A1 &a1 = a2;
      cout << "Calling a1.print(): ";
      a1.print();
      B2 b2;
      cout << "Calling b2.print(): ";
      b2.print();
      B1 &b1 = b2;
      cout << "Calling b1.print(): ";
      b1.print();
      return 0;
    }
    

    Output:

    Calling a2.print(): A2::print() called.
    Calling a1.print(): A2::print() called.
    Calling b2.print(): B2::print() called.
    Calling b1.print(): B1::print() called.
    

    Life demo on ideone