C ++ base class inheritance and polymorphism

C ++ base class inheritance and polymorphism

 

Virtual function:

Virtual functions of subclasses will override functions of the same name of the base class.

 

Non-virtual function:

What kind of pointer declaration is, you can only access the functions owned by the class. .

Pay special attention to what type the pointer is declared. . . . It has nothing to do with its new type. . . Irrelevant. .

 

class Base
{
public:
    Base(){};
    ~Base(){};
public:
    virtual void printHello()
    {
        cout << "Base: Base say hello"<<endl;
    }

    void printName()
    {
        cout << "Base: I am Base" << endl;
    }

    void printDate()
    {
        cout << "Base: Base 6666" << endl;
    }
};

class Drive : public Base
{
public:
    Drive(){};
    ~Drive(){};
public:
    virtual void printHello()
    {
        cout << "Drive: Drive say hello" << endl;
    }

    void printName()
    {
        cout << "Drive: I am Drive" << endl;
    }

    void printAge()
    {
        cout << "Drive: Age 29"<< endl; 
    } 

}; 



int main ( int argc, char * argv []) 
{ 
    // Test1 ();
     // Test2 ();
     // Test3 ();
     // Test4 ();
     // Test5 ();
     // Test6 ();
     // Test7 (); 

    Base * objB1 = new Drive (); 
    objB1- > printHello (); 
    objB1- > printName (); 
    objB1- > printDate ();
 //     objB1-> printAge () ;   // The compiler will report an error

/// TheThe output is as follows: 
//   Drive: Drive say hello
 //   Base: I am Base
 //    Base: Base 6666 


    cout << endl; 
    system ( " pause " );
     return  0 ; 
}

 

Guess you like

Origin www.cnblogs.com/music-liang/p/12726786.html