Best Methods for Dynamically Creating New Objects

Posted by frankV on Stack Overflow See other posts from Stack Overflow or by frankV
Published on 2012-11-14T03:51:10Z Indexed on 2012/11/14 5:00 UTC
Read the original article Hit count: 102

Filed under:
|
|

I'm looking for a method to dynamically create new class objects during runtime of a program. So far what I've read leads me to believe it's not easy and normally reserved for more advanced program requirements.

What I've tried so far is this:

// create a vector of type class
vector<class_name> vect;

// and use push_back (method 1)
vect.push_back(*new Object);

//or use for loop and [] operator (method 2)
vect[i] = *new Object;

neither of these throw errors from the compiler, but I'm using ifstream to read data from a file and dynamically create the objects... the file read is taking in some weird data and occasionally reading a memory address, and it's obvious to me it's due to my use/misuse of the code snippet above.

The file read code is as follows:

// in main
ifstream fileIn
fileIn.open( fileName.c_str() );

// passes to a separate function along w/ vector
loadObjects (fileIn, vect);

void loadObjects (ifstream& is, vector<class_name>& Object) {
    int data1, data2, data3;
    int count = 0;
    string line;

    if( is.good() ){
        for (int i = 0; i < 4; i++) {    
            is >> data1 >> data2 >> data3;
            if (data1 == 0) {
                vect.push_back(*new Object(data2, data3) )
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about vector