On 2009-02-10 08:02:31 -0500, Kagamin <[email protected]> said:

Well, you can pass descendant objects :) I was surprised by this destructive feature. But code is still not polymorphic. Consider the following code:

class C
{
    public:
        virtual char* doSomething( C src )
                {
                        return src.Method();
                }
        virtual char* Method()
                {
                        return "It's C.";
                }
};

class C2 : public C
{
    public:
        virtual char* Method()
                {
                        return "It's C2.";
                }
};

int main(void)
{
    C c;
    C2 c2;
    printf("%s\n",c.doSomething(c));
    printf("%s\n",c.doSomething(c2));
    return 0;
}

What do you think is its output?

Since you're passing c2 as a C by value to doSomething, slicing do occur and it prints "It's C." two times. That's why in C++ we generally pass objects by reference. Unfortunately, you often can't do that for return values..

--
Michel Fortin
[email protected]
http://michelf.com/

Reply via email to