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!

2
  • 3
    That's overriding, not overloading. Commented Feb 21, 2011 at 12:31
  • B overrides WhoAreYou. Overloading would mean it also exists with a different set of arguments( e.g. WhoAreYou(int) ) Commented Feb 21, 2011 at 12:32

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

4 Comments

This works! Didn't know that there is a defference between pointers and normal objects in this case. Thanks!
Or use a reference: A& a = b;.
@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.
Hey xtofl, I saw your answer and wanted to mark it as correct. But you deleted it...
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.