Home >Backend Development >C++ >Will Polymorphism Work with Vector References in C ?
When working with vectors and polymorphism in C , one may encounter a situation where the stored object's type is crucial. Consider the following example:
<code class="cpp">struct Instruction { virtual void execute() { } }; struct Add : public Instruction { int a, b, c; Add(int x, int y, int z) { a = x; b = y; c = z; } void execute() { a = b + c; } }; vector<Instruction> v; Instruction* i = new Add(1, 2, 3); v.push_back(*i);</code>
In this code, a vector of base class objects is created, and an object of a derived class (Add) is pushed into the vector as a reference. The concern arises when accessing the "execute" function on this object:
<code class="cpp">auto ins = v.back(); ins.execute(); // Will the object retain its Add type?</code>
Will Polymorphism Work?
No, it won't. The vector stores values, not references. Therefore, when the Add object is pushed into the vector, it will be copied, resulting in an object of type Instruction, not Add.
Reference_wrapper
To ensure the polymorphism remains intact, one approach is to use std::reference_wrapper
<code class="cpp">vector<std::reference_wrapper<Instruction>> ins;</code>
Preventing Memory Leaks
Additionally, the code allocates an Add object dynamically with new without deleting it, causing a memory leak. To rectify this, the code should use a smart pointer, such as std::unique_ptr, or manually delete the object before it goes out of scope.
The above is the detailed content of Will Polymorphism Work with Vector References in C ?. For more information, please follow other related articles on the PHP Chinese website!