C ++ programming POJ "" WEEK6 polymorphism and virtual functions "" The principle of polymorphism "" virtual table "

The key "polymorphic" is characterized by a pointer or reference to the base class invoked
when a virtual function, the compiler is called uncertainty in the end time is the base class is also
a function of the derived class, called ---- OK "when run dynamic
build . " " Dynamic binding ," the end is how to achieve it?

#include<iostream>
using namespace std;
class Base {
public:
    int i;
    virtual void Print()
    {
        cout << "base:print";
    }
};

class Derived :public Base
{
public:
    int n;
    virtual void Print()
    {
        cout << "drived:print" << endl;
    }
};

int main ()
{
    Derived d;
    cout << sizeof(Base) << "," << sizeof(Derived);
    while (1);
    return 0;
}
// running output: 8, 12
 // Why are more than 4 bytes?

--- virtual function table key polymorphic implementation of
each class has virtual functions (virtual function or derived class)
has a virtual function table, any object class are placed in the virtual function
pointer table . Virtual function table lists the address of the class virtual functions. Multi-
out of the four bytes is used to put the address of the virtual function table .

 

#include<iostream>
using namespace std;
class A
{
public:
    virtual void Func()
    {
        cout << "A::FUNC" << endl;
    }
};
class B :public A
{
public:
    virtual void Func()
    {
        cout << "B::func" << endl;
    }
};
int main ()
{
    A a;
    A * PA = new new B ();
     // 64-bit program pointer is 8 bytes 
    Long  Long * P1 = ( Long  Long *) & A ;
     Long  Long * P2 = ( Long  Long * ) PA;
     * * P2 = P1; / / change virtual function table of contents 
    PA -> Func ();
     the while ( . 1 );
     return  0 ;

}
// B::Func
// A::Func

 

Guess you like

Origin www.cnblogs.com/focus-z/p/11080080.html