开发者

C++ real method overloading?

I have the classes A and B. B derives from A and overloads the method WhoAreYou(), when I now create a variable of type A and set the value to a B object and then call WhoAreYou(), the method of A is called. Look at this:

class A{
public:
    virtual void WhoAreYou(){
        cout << "I am A!"<<endl;
    }
};
class B: public A{
public:
    void WhoAreYou(){
        cout << "I am B!" &开发者_开发技巧lt;< endl;
    }
};


int main(int argc, char ** argv){
    A a = B();
    a.WhoAreYou(); //Output: I am A!
}

Is there a way to overload the method so, that in this case the WhoAreYou() method of B would be called? When I must cast the object first, a method overloading doesn´t really make sense in my opinion...

Thanky for your help!


Your "a" variable is an A, not a B. A a = B(); creates a new temporary B, then creates an A by copying the A part of B.

Try this:

B b;
A * a = &b;
a->WhoAreYou();


The problem has to do with slicing. I asked the exact same question with this topic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜