polymorphic C++ references

前端 未结 7 1058
闹比i
闹比i 2020-12-09 09:07

I was wondering how you can do polymorphism with references, as opposed to pointers.

To clarify, see the following minimal example:

cl         


        
7条回答
  •  Happy的楠姐
    2020-12-09 09:57

    I realize this is a really old post but there is another option you have for handling references for dynamically allocated objects. You can assign a reference to the dynamically allocated object. Below is some dummy code to give you an idea of how this works.

    struct A
    {
      int b;
      virtual void print();
      A(int val):b(val) {}
    };
    
    struct A_child:public A
    {
      A_child(int val):A(val) {}
      void print();
    };
    
    void A:print()
    {
    cout<<"parent\n";
    }
    
    void A_child:print()
    {
    cout<<"child\n";
    }
    
    struct test_ref
    {
    A *& ref;
    test_ref(A * ptr) : ref(ptr)
    }
    
    int main()
    {
    
      test_ref parent(new A(12));
      parent.ref->print();
    
      test_ref child(new A_child(15));
      child.ref->print();
    } 
    

    To be honest I am not certain when this is a good idea. I just wanted to show an alternative approach where you dont have to dereference the dynamically allocated memory when initializing an object.

    I am also pretty certain dynamically allocating a pointer while initializing a class where the pointer is stored as a reference pointer will probably lead to a memory leak unless you can delete the reference pointer.

提交回复
热议问题