简体   繁体   中英

How can a pointer to a derived class pointing to the object of base class can access function of both class?

    class A {
    public: 
        int a = 5;
        int geta(){return a;}
};

class B : public A {
    public:
        int b = 6;
        int getb(){return b;}
};

int main(){
    A a;
    B* b = (B*) &a;
    cout<<b->geta()<<endl;   
    cout<<b->getb();
}

Output: 5
5

Questions: why does both giving same results?
How does casting works internally?

currently I am using: Thread model: win32

gcc version 9.2.0 (GCC)

why does both giving same results?

Because the behaviour of the program is undefined.

How does casting works internally?

This cast doesn't "work". The behaviour of the program is undefined.


Some extra explanation.

(B*) &a

This here is a C style cast. Don't use C style casts . It can mean different things in different contexts. In this case, it means a static cast from the base class pointer to a derived class pointer.

When you static cast to a derived type that isn't the dynamic type (or a base of the dynamic type) of the object, the behaviour of the program is undefined. Don't downcast to a type that isn't the dynamic type (or base) of the object .

If you don't know what the dynamic type is 1 , then dynamic_cast is a safer option, since you can check for null in case your guess was wrong. That said, if you need to down cast without knowing the derived type, then your design is likely bad and you probably should have been writing a virtual function instead.

Another rule of thumb: If you don't know what you're doing, then adding casting will create problems for you. Study what casting means before using it at random.

1 This is a hypothetical discussion about where a downcast might be used. In this case you should know that the dynamic type isn't the one that you're casting to, so any cast to that type would be pointless.

Answering question How does casting works internally? as it seems to be missed by another answer.

Internally, your c-style cast is treated with static_cast . static_cast down the hierarchy is only allowed when the dynamic type of the object being pointer (or referenced) to matches the cast. In your case, it does not - the dynamic type of the object is still A .

But the static_cast doesn't really check for dynamic object type (this is while it is called static), it allows programmer to basically say: "Trust me, I know what I am doing". So compiler obliges and believes you, and generates code which would work correctly in assumption that dynamic type is what you tell it is.

In your case, though, it is not - so compiled program behaves unexpectedly.

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