I'm actually new to C ++. I tried something (actually a card container), but it doesnβt work the way I assumed that ... Before sending my code, I will explain it soon.
I created 3 classes:
ClassA ClassDerivedA ClassAnotherDerivedA
The last two are derived from "ClassA".
Next, I created a map:
map<string,ClassA> test_map;
I put some objects on the map (from Type ClassDerivedA and ClassAnotherDerivedA). Keep in mind: the displayed value is of type ClassA. This will only work because of polymorphism. Finally, I created an iterator that runs my map and compares the user input with my keys on the map. If they match, it will call a special method called printOutput.
And there is a problem: Although I declared "printOutput" as "virtual", the only method is called one of my base class, but why? and here is the code:
#include <iostream>
#include <map>
using namespace std;
class ClassA
{
public:
virtual void printOutput() { cout << "ClassA" << endl; }
};
class ClassDerivedA : public ClassA
{
public:
void printOutput() { cout << "ClassDerivedA" << endl; }
};
class ClassAnotherDerivedA: public ClassA
{
public:
void printOutput() { cout << "ClassAnotherDerivedA" << endl; }
};
int main()
{
ClassDerivedA class_derived_a;
ClassAnotherDerivedA class_another_a;
map<string,ClassA> test_map;
test_map.insert(pair<string,ClassA>("deriveda", class_derived_a));
test_map.insert(pair<string,ClassA>("anothera", class_another_a));
string s;
while( cin >> s )
{
if( s != "quit" )
{
map<string,ClassA>::iterator it = test_map.find(s);
if(it != test_map.end())
it->second.printOutput();
}
else
break;
}
}
source
share