How can I create a polymorphic object on the stack?

前端 未结 12 1750
谎友^
谎友^ 2021-01-12 05:40

How do I allocate a polymorphic object on the stack? I\'m trying to do something similar to (trying to avoid heap allocation with new)?:

A* a = NULL;

switch         


        
12条回答
  •  日久生厌
    2021-01-12 06:34

    trying to avoid heap allocation with new)?

    Well in that case you create object on stack as usual and assign address to the base pointer. But remember, if this is done inside a function, don't pass the address as return value, because stack will unwind after the function call returns.

    So this is bad.

    A* SomeMethod()
    {
        B b;
        A* a = &b; // B inherits from A
        return a;
    }
    

提交回复
热议问题