Understanding Calling a Virtual Function During c++ Inheritance

Asked 2 years ago, Updated 2 years ago, 69 views

I have a question about the virtual function of c++.
Prepare a very simple base and inherited Derived as follows:

#include<iostream>

US>structure Base {
virtual void f()
{
   std::cout<<"Base"<<std::endl;
}
};

structure Derived:Base {
void f() override
{
    std::cout<<"Derived"<<std::endl;
}
};

int main()
{
  {
    Derived d;
    Base b = d;

    b.f();
  }

  {
    Derived d;
    Base & b = d;

    b.f();
  }
}

The results of the run are:

Base
Derived

will be

Why does the former call the base f()?

c++ c++11

2022-09-30 21:27

1 Answers

Baseb=d;

means creating a new instance of type Base and using d as the initialization value.In other words, b is the Base itself, so f() of Base is called

.
Base&b=d;

b is a reference type, so the contents are d.Therefore, f() in Derived is called

.


2022-09-30 21:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.