Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ Printing Data on a STL list
    primarykey
    data
    text
    <p>I have a Base class, and a Derived class; on the other hand I made a List class that uses the STL . Base class has a virtual function called <code>PrintData()</code>, that prints an integer that belongs to the Base class. In the Derived class; the same function <code>printData()</code> prints an integer that belong to the Derived and the other one from the Base class.</p> <p>The thing is that, in the class List, I'm just getting the data from Base, no matter if I inserted a Derived instance on the list.</p> <p>I need to print Derived data, that is supposed to have Base data as well. Here is the code:</p> <pre><code> #pragma once; #include &lt;iostream&gt; #include &lt;sstream&gt; using namespace std; class Base{ protected: int x; public: Base(){ x=3; } void setX(int a){ x=a; } int getX(){ return x; } virtual string printData(){ stringstream f; f&lt;&lt;getX()&lt;&lt;endl; return f.str(); } }; class Derived : public Base{ int a; public: Derived(){ this-&gt;Base::Base(); a=4; } void setA(int x){ a=x; } int getA(){ return a; } string printData(){ stringstream a; a&lt;&lt;getA()&lt;&lt;getX()&lt;&lt;endl; return a.str(); } }; </code></pre> <p>And here is the List class:</p> <pre><code> #pragma once; #include "Prueba.cpp" #include &lt;list&gt; class Lista{ list&lt;Base*&gt; lp; public: Lista(){ } void pushFront(Base* c){ lp.push_front(c); } void pushBack(Base* c){ lp.push_back(c); } void printList(){ list&lt;Base*&gt;::const_iterator itr; for(itr=lp.begin(); itr!=lp.end(); itr++){ cout&lt;&lt;(*itr)-&gt;printData(); } } ~Lista(){ } }; int main(){ Derived* d=new Derived(); Lista* l=new Lista(); l-&gt;pushFront(d); l-&gt;printList(); system("Pause"); return 0; } </code></pre> <p>I'm just getting the Base class data, that is an integer with the value of 3. But I'm not getting the integer from Derived that has the value of 4.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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