Need help with a map (C ++, STL)

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;
    }

}
+3
source share
3 answers

The problem is the cut. You save the values ClassAon the map. When you store instances of a derived class in a map, you can slice objects ClassA. You will need to store pointers on the map instead of values.

See additional section information: What is object splitting?

+13
source

C ++ is not Java. You cannot save a derived type in a variable of a base type. For instance:

Base b = Derived();

Derived b. , :

Base * b = new Derived();

++ - :

map <string, Base *> m;

++ - ?

+4

" slicing". , . , map ClassA:

map<string, ClassA *> test_map

, delete , , .

: ,

+4

Source: https://habr.com/ru/post/1745358/


All Articles