016 virtual functions

 

/ * 
Directory: 
    a concept of 
    two simple comparison 
* /    

 

A concept

/ * 

// virtual function     
    virtual function must override function, the override before the function added to the base class virtual 
    
    used: 
        Class 1 subject: what the object class corresponding to the function call override 
        2 base class pointer: 
            (1) an ordinary function call : class function corresponds to 
            (2) call virtual functions: class pointer 
    
    principle: 
        a plurality of target header pointer to the virtual table         
        
    thought: 
        abstract and implementation 
            base class: concepts, abstract 
            derived class: the object-specific 
        
        static binding and dynamic tie given 
            static: compile-time binding, by calling the object (object type) 
            dynamic: binding runtime by calling address (The virtual table) 
            
// pure virtual function: 
        a base class object can not be defined 
        for derived classes must override function 
        3 base class containing pure virtual function, called an abstract class. Pure virtual function is also called an abstract. 
* /

 

Two simple comparison

#pragma once
#include <iostream>

using namespace std;

class CBase
{
public:
    void RealFunc()
    {
        cout << "CBase::RealFunc()" << endl;
        m_i = 0x10;
    }
    virtual void VirtualFunc()
    {
        cout << "CBase::VirtualFunc()" << endl;
        m_i = 0x11;
    }

    int m_i;
};


class CDerived :public CBase
{
public:
    void RealFunc()
    {
        cout << "CDerived::RealFunc()" << endl;
        m_j = 0x20;
    }
    void VirtualFunc()
    {
        cout << "CDerived::VirtualFunc()" << endl;
        m_j = 0x22;
    }

private:
    int m_j = 0x88;
};


int main()
{
    CBase b;
    b.RealFunc();
    b.VirtualFunc();
    cout << sizeof(b) << endl;

    CDerived d;
    d.RealFunc();
    d.VirtualFunc();
    cout << sizeof(d) << endl;

    CBase *pb;
    pb = &b;
    pb->RealFunc();
    pb->VirtualFunc();

    pb = &d;
    pb->RealFunc();
    pb->VirtualFunc();


    return 0;
}

 

Guess you like

Origin www.cnblogs.com/huafan/p/11980699.html