views:

19

answers:

2

Say I got:

class X_
{
public:
    void do() { }
}

class Y_ : public X_
{
}

And I have this function:

void foo(X_ whatever)
{
  whatever.do();
}

Can I send a "Y_" object to the foo function, would this work?

I just realized that I could have tested this myself :)

+3  A: 

Yes, but it will get sliced - all the Y_ parts of the object will be chopped off, and it will become an X_. You normally need to pass by reference in this situation, as normally do() will be a virtual function:

void foo(X_ & whatever)   // ampersand means whatever is a reference
{
  whatever.do();
}

BTW, I don't know what you think those suffixed underscores are gaining you, but I would have said "nothing".

anon
+1  A: 

It will work to send it - yes, but as Neil points out the object will be sliced, i.e. an X_ object will be created based on the original Y_ object. A somewhat larger example:

class Base
{
public:
    int func() { return 1; }
    virtual virtfunc () { return 2; }
}

class Derived
{
public:
    int func() { return 3; } // Shadows (hides) Base::func. Never do this!
    virtual int virtfunc() { return 4; }
}

int testfunc(Base b) { return b.func(); }
int testvirtfunc(Base b) { return b.virtfunc(); }
int testfuncbyref(Base& b) { return b.func(); }
int testvirtfuncbyref(Base& b) { return b.virtfunc(); }

void main()
{
    Base b;
    Derived d;

    b.func(); // returns 1
    b.virtfunc(); // returns 2
    d.func(); // returns 3
    d.virtfunc(); // returns 4.

    testfunc(d); // returns 1 because func is non-virtual.
    testvirtfunc(d); // returns 2 because a Base instance is created by the call.
    testfuncbyref(d); // returns 1 because func is non-virtual.
    testvirtfuncbyref(d); // returns 4 because the real d object is used and the function is virtual.
}
Anders Abel