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
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
© 2024 OneMinuteCode. All rights reserved.