I am new to c++ programming and I have a basic issue, I want to create N objects, N is is actually a user input.
I am specific about having object names, say beam1, beam2,…,beamX.
2 quick things
- Is it possible in C++ to create dynamic object as this?
-
if it is how do we do tht? I am pasting code for your refrence..
#include "iostream" # include <conio.h> using namespace std; // Static member variable is defined outside the class.. class beam { public: int length; }; int main () { int i=0, no_of_spans, j; cout<< "Design Of a Continous Beam \n1) No Of Spans : "; cin >> no_of_spans; for (i =0; i < no_of_spans; i++) { j = i; beam; cout << "Length of Beam" << j+1 << " is : "; cin >> beami.length; } cout << "\nPress any key to continue..\n"; getch (); }
This is obviously a code with errors, its put up as an example to get the idea.
As has already been stated by others (Luchian, John, Component and Ed) you can use a
std::vectorand it will dynamically grow as necessary to store the number ofbeamobjects required.If you wish to refer to these objects later by name you could store them in a
std::map, with the key of the map being the object name (e.g. beam1, beam2, beam3, …, beamX):—
boost::lexical_cast<>is a mechanism for converting (in this case) anintto astd::string. There other ways to achieve this (usingstd::ostringstreamfor example).