In C ++, if a member function is virtual, when can static binding be used?

In C ++, when can a virtual function use static binding? If it is accessed through a pointer that is accessed directly or never?

+3
source share
3 answers

When a virtual method is invoked through a pointer or reference, dynamic binding is used. Compile time binding is used at any other time. Example:

class C;

void Foo(C* a, C& b, C c) {
  a->foo();  // dynamic
  b.foo();  // dynamic
  c.foo();  // static (compile-time)
}
+7
source

If you want to call the base class version of a function, you can do this by explicitly calling the base class:

class Base
{
public:
  virtual ~Base() {}
  virtual void DoIt() { printf("In Base::DoIt()\n"); }
};

class Derived : public Base
{
public:
  virtual void DoIt() { printf("In Derived::DoIt()\n"); }
};

Base *basePtr = new Derived;
basePtr->DoIt();  // Calls Derived::DoIt() through virtual function call
basePtr->Base::DoIt();  // Explicitly calls Base::DoIt() using normal function call
delete basePtr;
+6
source

, . , : , , , . , , ( , , , , , , undefined ). , , , , . !

+2
source

Source: https://habr.com/ru/post/1699188/


All Articles