As
Griff stated, you cannot do that.
An alternative could be using an
unordered_map
to link the user supplied string to newly constructed object. Try
#include <iostream>
#include <unordered_map>
using namespace std;
class Airplane
{
unsigned tons;
public:
Airplane(unsigned tons):tons(tons){}
Airplane():Airplane{100}{}
unsigned get_tons() const {return tons;}
};
int main()
{
string ap_name;
unsigned ap_tons;
unordered_map<string, Airplane> m_ap;
m_ap.emplace( "plane1", 100 );
m_ap.emplace( "plane2", 120 );
m_ap.emplace( "plane3", 130 );
cout << "weight of plane2 is " << m_ap["plane2"].get_tons() << "\n";
cout << "name your airplane: ";
cin >> ap_name;
cout << "specify its weight (tons): ";
cin >> ap_tons;
m_ap.emplace( ap_name, ap_tons );
for (auto const & [name, plane] : m_ap )
cout << "m_ap[" << name << "] weights " << plane.get_tons() << "\n";
}