简体   繁体   中英

Virtual and non-virtual functions during compile-time and runtime (C++)

I hope the title is not confusing. I am trying to understand the following issue that arises from defining methods of a class virtual or not in C++. Imagine I have a base class A and a derived class B, such that

class A { 
public:
    void print() { cout << "A"; } 
}

class B : A { 
public:
    void print() { cout << "B"; } 
}

If I know execute the code below, the print command would print out "A".

A *a = new A();
B *b = new B();
((A *)b)->print(); // this prints "A"

However , if I declare the "print" methods in both classes as virtual, I would instead see a "B" printed in my screen. Why is this happening exactly?

If a function is NOT virtual , the compiler will just use whatever type the expression gives. So when you cast a B object to an A object, it will call the A::print function.

If you use virtual , a table of function pointers [1] is built by the compiler, and when the function is to be called, the compiler generates code to call through that table, rather than just looking at the current type, which allows a base-type to call function in a derived class, and thus allowing polymorphic behaviour.

[1] technically, the specification doesn't tell us how to implement this, but this is how nearly all compilers work. If the compiler can produce the same behaviour using magic, it is allowed to do so - as long as the magic is reliable and reproducable.

A *b = new B(); //LHS is compile time = RHS is runtime(coz' object is created at runtime)
B.print();

if print is non virtual :
Compile time: A.print() is resolved to goto work (since it is a real function)
Runtime : A.print() is deployed/dispatched to work.

If print is a Virttual/ not real funtion:
Compile time: A.print() is bypassed and B.print is resolved to goto work runtime: B.print() is deployed/dispatched to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM