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 PrintData(), that prints an integer that belongs to the Base class. In the Derived class; the same function printData() prints an integer that belong to the Derived and the other one from the Base class.
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.
I need to print Derived data, that is supposed to have Base data as well.
Here is the 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 is the 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 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.
Replace
with
and run it again. I suspect that your code does print both values, only it disguises the fact. The new line strips the disguise away, so to speak.
By the way, @MarkRansom is right. It is not necessary to call the Base constructor explicitly. (In fact, when I tried your code, my compiler wouldn’t even allow it.)