Question

I'm wondering how I can set the name of an instance of a class to be a variable. Here's the code that I've got so far:

char line;
int A, B, C;
cout << "Enter a name and an equation for the line (example: g 5 2 1):" << endl;
cin >> line >> A >> B >> C;
Line line;
line.A = A;
line.B = B;
line.C = C;
cout << line << ": " << A << "x + " << B << "y + " << C << " = 0" << endl;
return 0;

Needless to say - class Line has variables A, B and C.

So for example - when the users enters "m 2 3 1" I want to create a new Line with an instance name "m" and A=2, B=3, C=1. If the user were to enter "s 2 2 2" - create a Line instance "s" with A=2, B=2, C=2, and so on. And maybe later if the user adds a line name that already exists, he will get an error message.

So, to sum it up can anyone tell me the correct way to create this kind of instances with dynamic names?

Thank you in advance : ]

Was it helpful?

Solution

Since variable names are just compile type names for human interaction with source code you can't directly do it.

The easiest way would be to use a map (which is basically an associative array, no actually it isn't but from what you need to know for your problem it is) to obtain what you need:

#include <map>

std::map<string, Line> lines;

Line line = Line(A,B,C)
string name = "lineName";
lines[name] = line;
...
std::map<string,Line>::iterator it = lines.find(name);
if (it != lines.end())
{
  const Line& line = it->second;
  ..
}

OTHER TIPS

So, to sum it up can anyone tell me the correct way to create this kind of instances with dynamic names?

You can't. The closest you can get is using an std::map:

std::map<std::string, Line> vars;

int a = 0;
int b = 0;
int c = 0;
std::string name;
std::cin >> name >> a >> b >> c;
vars.emplace(std::make_pair(name, Line { a, b, c }));

If you enter s 1 2 3 you can get the corresponding Line object with vars["s"].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top