How can I create a polymorphic object on the stack?

前端 未结 12 1731
谎友^
谎友^ 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:25

    If B is your base types D1, D2, and D3 are your derived types:

    void foo()
    {
        D1  derived_object1;
        D2  derived_object2;
        D3  derived_object3;
        B *base_pointer;
    
        switch (some_var)
        {
            case 1:  base_pointer = &derived_object1;  break;
            ....
        }
    }
    

    If you want to avoid wasting the space of the three derived objects, you could break up your method into two parts; the part that chooses which type you need, and the part of the method that works on it. Having decided which type you need, you call a method that allocates that object, creates a pointer to it, and calls the second half of the method to complete the work on the stack-allocated object.

提交回复
热议问题