Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to copy an inherited class from its base class pointer without splicing?
    text
    copied!<p>I am having some trouble with trying to create a copy of a class from a pointer to its base class. It is best illustrated through this example:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; class Base { public: Base() { } virtual void test() { std::cout &lt;&lt; "I am just the base class\n"; } }; class First : public Base { public: First() { } void test() { std::cout &lt;&lt; "This is the First class\n"; } }; class Second : public Base { public: Second() { } void test() { std::cout &lt;&lt; "This is the Second class\n"; } }; int main() { First *f = new First(); Second *s = new Second(); // First, I keep a vector of pointers to their base class std::vector&lt;Base *&gt; ptrs; ptrs.push_back(f); ptrs.push_back(s); ptrs[0]-&gt;test(); // Properly calls the implemented virtual class by inheritor ptrs[1]-&gt;test(); // Properly calls the implemented virtual class by inheritor // Now, I want to *copy* the class without it being spliced to just the base class // from the ptrs vector (not from 'f') First *f2 = new First(*ptrs[0]); } </code></pre> <p>The error I end up getting is:</p> <pre><code>test.cpp: In function ‘int main()’: test.cpp:35: error: no matching function for call to ‘First::First(Base&amp;)’ test.cpp:12: note: candidates are: First::First() test.cpp:10: note: First::First(const First&amp;) </code></pre> <p>Is there any way to cast this pointer to copy the full objected, and not just the base class? Or do I need to store a pointer to the inheritor to make this work?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload