c++polymorphism

Polymorphic objects on the stack?


In Why is there no base class in C++?, I quoted Stroustrup on why a common Object class for all classes is problematic in c++. In that quote there is the statement:

Using a universal base class implies cost: Objects must be heap-allocated to be polymorphic;

I really didn't look twice at it, and since its on Bjarnes home page I would suppose a lot of eyes have scanned that sentence and reported any misstatements.

A commenter however pointed out that this is probably not the case, and in retrospect I can't find any good reason why this should be true. A short test case yields the expected result of VDerived::f().

struct VBase {
    virtual void f() { std::cout <<"VBase::f()\n"; }
};

struct VDerived: VBase {
    void f() { std::cout << "VDerived::f()\n"; }
};

void test(VBase& obj) {
    obj.f();
}

int main() {
    VDerived obj;
    test(obj);
}

Of course if the formal argument to test was test(VBase obj) the case would be totally different, but that would not be a stack vs. heap argument but rather copy semantics.

Is Bjarne flat out wrong or am I missing something here?

Addendum: I should point out that Bjarne has added to the original FAQ that

Yes. I have simplified the arguments; this is an FAQ, not an academic paper.

I understand and sympathize with Bjarnes point. Also I suppose my eyes was one of the pairs scanning that sentence.


Solution

  • Looks like polymorphism to me.

    Polymorphism in C++ works when you have indirection; that is, either a pointer-to-T or a reference-to-T. Where T is stored is completely irrelevant.

    Bjarne also makes the mistake of saying "heap-allocated" which is technically inaccurate.

    (Note: this doesn't mean that a universal base class is "good"!)