As far as I know, in your case lstClientes must contain pointers, because std::list stores a copy of the object.
In your case, lstClientes contains objects of type Cliente, even if you push_back ClienteJuridico or ClienteNatural.
Changing lstClientes to list<Cliente*> will solve your problem.
Obviously, be careful of memory leaks.
Maybe you would use manager pointers: see http://www.cplusplus.com/reference/memory/
You must make the base's class a virtual method.
About copying, you should store pointers instead of objects (if you are allowed to).
This is kind of what you should have:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class BaseClient {
public:
virtualvoid Display() =0;
virtual ~BaseClient() {} // Important!
// If you split header/source, put the (empty) body in the source file.
};
class JurClient : public BaseClient {
public:
virtualvoid Display() { std::cout << "Jur. Client"; }
};
class NatClient : public BaseClient {
public:
virtualvoid Display() { std::cout << "Nat. Client"; }
};
And the rest of the code should be like this:
1 2 3 4 5 6 7 8 9 10 11
std::list<std::unique_ptr<BaseClient>> clients;
clients.push_back(std::unique_ptr<BaseClient>(new JurClient()));
clients.push_back(std::unique_ptr<BaseClient>(new NatClient()));
unsignedint ClientID = 0;
for(autoconst& it : clients)
{
std::cout << "Client nr. " << ++ClientID << " is a ";
it->Display();
std::cout << std::endl;
}
Some of the code uses C++11 features (such as std::unique_ptr and range-for.
If you really want to follow a different approach, store all the infos in a single class as follows:
enum ClientType {
CT_NATURAL = 0, // = 0 is important
CT_JURIDICA,
CT_AMOUNT // must be the last one, tells us how many types are there
};
class Client {
ClientType m_ClientType;
public:
Client(ClientType t = CT_NATURAL) // If no ClientType is provided, use CT_NATURAL.
: m_ClientType(t) {}
void Display() const { // Note: Marked as const, since it doesn't modify Client itself.
// static: initialized once
// const: does not change
staticconst std::string TypeToName[CT_AMOUNT] = {
"Persona Natural",
"Persona Juridica"
};
if(m_ClientType < 0 || m_ClientType >= CT_AMOUNT)
std::cout << "Tipo no definido";
else
std::cout << TypeToName[m_ClientType];
}
};
And use as follows:
1 2 3 4 5 6 7 8 9 10 11 12
std::list<Client> clients;
clients.push_back(Client(CT_NATURAL));
clients.push_back(Client(CT_JURIDICA));
clients.push_back(Client(ClientType(42))); // client type of id 42? it does not exist, and will print Tipo no definido.
unsignedint ClientID = 0;
for(autoconst& it : clients)
{
std::cout << "Client nr. " << ++ClientID << " is a ";
it.Display();
std::cout << std::endl;
}