简体   繁体   中英

How can a derived class pointer to a base class object call methods of the derived class?

class BaseClass{

public:
    int a;
    char buf[250];

    void abcd(){
        cout<<"hello base from abcd";
    }

    virtual void defg(){
        cout<<"hellow base from defg";
    }
};

class DerivedClass: public BaseClass{

public :
    int b;
    char bufb[255];

    void bcde(){
        cout<<"hello base from bcde";
    }

    virtual void defg(){
        cout<<"hellow base from defg";
    }
};

int main(){

    BaseClass* bas=new BaseClass();
    DerivedClass* der;

    der=static_cast<DerivedClass*>(bas);
    cout<<"address of der ="<<der <<"   base= "<<bas<<endl;
    der->bcde();
    cout<<endl<<"Base size:"<< sizeof(*bas)<<"  Derived size:"<<sizeof(*der)<<endl;

    getch();
    return 0;
}

How can derived class pointer to base class object can call methods of derived class. WHY and HOW ? As base class object created in memory is of only size of base class, how could it contains derived class methods. and it successfully got called.

OutPut:==>

address of der =002585A8 base= 002585A8

hello base from bcde

Base size:260 Derived size:520

By casting the pointer to DerivedClass* , when the most derived object is of type BaseClass , and by then using that pointer to access DerivedClass stuff, you have Undefined Behavior , UB. One possible effect of UB is that what one mistakenly believed would happen, happens. Other possibilities include crashes, hangs and weird results.

In practice, since DerivedClass::bcde() doesn't access any data in the instance, and doesn't call any virtual function, the only possible crash cause would be explicit checking inserted by the compiler.

I do not know of any compiler that adds such checking, but the compiler is free to do so, and generally it's free to just assume that UB will not happen.

The compiler bound the non-virtual method bcde based purely on the type information. As the method doesn't refer to the object contents, memory layout did not come into play.

You have a mistakes in the output messages

class DerivedClass: public BaseClass{

public :
    int b;
    char bufb[255];

    void bcde(){
        cout<<"hello base from bcde";
    }

    virtual void defg(){
        cout<<"hellow base from defg";
    }
};

DerivedClass should print "hello der from bcde", not "hello base from bdce". And actually your code prints message from DerivedClass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM