How to call a virtual function of a derived class using a base class pointer

Take a look at this code:

class CBase
{
 public:
    virtual vfunc() { cout << "CBase::vfunc()" << endl; }
};

class CChild: public CBase
{
 public:
    vfunc() { cout << "CChild::vfunc()" << endl; }
};

int main() 
{
 CBase *pBase = new CBase;
 ((CChild*)pBase)->vfunc(); // !!! important 
 delete pBase;
 return 0;
}

Conclusion:

CBase::vfunc()

But I want to see: CChild :: vfunc ()

Explicit ((CChild *) pBase) uses the type "CChild *". So, why to call the derived vfunc () I need to replace the “important” line: ((CChild *) PBase) → CChild :: vfunc ();

+5
source share
4 answers

This is not how it works - it is:

CBase *pBase = new CChild;
pBase->vfunc();

virtualfunction calls are solved dynamically by pointers and links (unless you call the method explicitly, as you did). This means that it does not matter what you tell the compiler, a pointer, it will look for a method in vftable. In your case it is vftableof CBase.

+6

. *pBase - CBase. , CChild, CChild.

, CChild*, undefined.

+5

- : CChild (, , ), dynamic_cast downcast. dynamic_cast , .

: http://msdn.microsoft.com/en-us/library/cby9kycs(v=vs.80).aspx

CBase CChild dynamic_cast, CChild dynamic_cast, , CChild CChild.

+2

. CBase CChild! . ...

#include <iostream>

class CBase {
public:
    virtual void vfunc() { std::cout << "CBase::vfunc()" << std::endl; }
    virtual ~CBase(){} // Virtual destructor... extremely important! I'll let you figure out why as an excercise
};

class CChild: public CBase {
public:
    void vfunc() { std::cout << "CChild::vfunc()" << std::endl; }
    ~CChild(){} // Is this destructor called? When? Try adding some std::cout to each destructor
};

int main() 
{
    CBase *ptr1 = new CBase;
    CBase *ptr2 = new CChild;

    ptr1->vfunc(); // ptr1 points to an instance of CBase. This is what important!!
    ptr2->vfunc(); // ptr2 points to an instance of CChild, which can be referenced to as a CBase

    delete ptr1;
    delete ptr2;
}

:

CBase::vfunc()
CChild::vfunc()

PS: , 5 , , !

0

All Articles