C++ Printing Data on a STL list -


i have base class, , derived class; on other hand made list class uses stl . base class has virtual function called printdata(), prints integer belongs base class. in derived class; same function printdata() prints integer belong derived , other 1 base class.

the thing that, in class list, i'm getting data base, no matter if inserted derived instance on list.

i need print derived data, supposed have base data well. here code:

 #pragma once; #include <iostream> #include <sstream> 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<<getx()<<endl;         return f.str();     } };  class derived : public base{      int a;  public:     derived(){         this->base::base();         a=4;     }     void seta(int x){         a=x;     }     int geta(){         return a;     }     string printdata(){         stringstream a;         a<<geta()<<getx()<<endl;         return a.str();     }   }; 

and here list class:

 #pragma once; #include "prueba.cpp" #include <list>      class lista{         list<base*> lp;     public:         lista(){          }          void pushfront(base* c){             lp.push_front(c);         }          void pushback(base* c){             lp.push_back(c);         }          void printlist(){              list<base*>::const_iterator itr;                 for(itr=lp.begin(); itr!=lp.end(); itr++){                      cout<<(*itr)->printdata();                   }         }           ~lista(){          }     };      int main(){         derived* d=new derived();         lista* l=new lista();         l->pushfront(d);         l->printlist();         system("pause");         return 0;     } 

i'm getting base class data, integer value of 3. i'm not getting integer derived has value of 4.

replace

    a<<geta()<<getx()<<endl; 

with

    a<<geta()<<" "<<getx()<<endl; 

and run again. suspect code print both values, disguises fact. new line strips disguise away, speak.

by way, @markransom right. not necessary call base constructor explicitly. (in fact, when tried code, compiler wouldn't allow it.)


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -