1

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!" << 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!

Van Coding
  • 24,244
  • 24
  • 88
  • 132

2 Answers2

5

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();
Erik
  • 88,732
  • 13
  • 198
  • 189
  • This works! Didn't know that there is a defference between pointers and normal objects in this case. Thanks! – Van Coding Feb 21 '11 at 12:33
  • 2
    Or use a reference: `A& a = b;`. – xtofl Feb 21 '11 at 12:36
  • 1
    @FlashFan: Your variable "a" *is* an A. Nothing you do will change that, you declared it to be an A. Using references or pointers, you can refer to or point to something else, which is *at least* an A, as my sample shows. – Erik Feb 21 '11 at 12:37
  • Hey xtofl, I saw your answer and wanted to mark it as correct. But you deleted it... – Van Coding Feb 21 '11 at 12:39
1

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

Community
  • 1
  • 1
Marlon
  • 19,924
  • 12
  • 70
  • 101