c++ - How functions are resolved by compiler? -


how determined whether below call bound @ compile time or @ runtime?

object.member_fn;//object either base class or derived class object p->member_fn;//p either base class or derived class pointer 

edited:

#include <iostream> using namespace std; class base {        public:           base(){ cout<<"constructor: base"<<endl;}           ~base(){ cout<<"destructor : base"<<endl;} }; class derived: public base {      //doing lot of jobs extending functionality        public:            derived(){ cout<<"constructor: derived"<<endl;}            ~derived(){ cout<<"destructor : derived"<<endl;}  }; void foo() {     base & var = derived();     base*pvar = new derived;     delete pvar; } void main() {     foo();         std::cin.get(); }   out put: constructor: base constructor: derived constructor: base constructor: derived destructor : base // derived not called,                   // pval of type base* , fn not virtual                    //so compile time binding destructor : derived destructor : base 

if the method not virtual, both calls resolved @ compile time. if method virtual first call in question (obj.method()) resolved @ compile time object, @ runtime reference. second call (objp->method()) resolved @ runtime. can force @ compile time call non-derived version of method.

struct base {    void f();    virtual void v(); }; struct derived : public base {    void f();    void v(); // intentionally left virtual out, not matter }; int main() {    derived d;    base & b = d;    base * bp = &d;     // compile time:    d.f();   // derived::f    d.v();   // derived::v    b.f();   // base::f   -- non-virtual    bp->f(); // base::f   -- non-virtual     // runtime:    b.v();   // derived::v    bp->v(); // derived::v     // compile time (user forced):    b.base::v();   // base::v    bp->base::v(); // base::v } 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -