0

Let's say I have a Class Box

class Box{
    ...
};

and I need to create boxes based on users input. I tried to make a Blueprint Object

Method 1:

int main(){
    Box box; //Blueprint
    vector<Box> boxes;
    for(int i = 0; i < 5; i++) //Creates 5 boxes
        boxes.push_back(box);

    return 0;
}

This works. It creates a Vector with 5 Box Objects. But then I tried to do the following so I can set values every-time I create one Object with the constructor

Method 2:

int main(){
    vector<Box> boxes;

    for(int i = 0; i < 5; i++){ //Creates 5 boxes
        //Lets assume we input x and y every time
        Box box(x, y);
        boxes.push_back(box);
    }

    return 0;
}

This seems to be working just fine, when use boxes[i].x it gives me the value of x as it should. Note that x and y are Public and not Private for the simplicity of the example.

I saw this post, where the user patrick explained how to create Objects Dynamically using a lot of classes named Factories of Boxes for example and I did not understand you have to complicate it so much instead of using one of the two methods I tried in this post and worked for me.

My questions are:

  1. Are my methods the right way to make objects based on the users input
  2. If yes, which one of my methods is the best out of the two
  3. What is the difference between my way and patrick's from the other post

The original program I am making has a class named AI and I want to make more Objects of this class based on how many AI the user wants to play against.

Community
  • 1
  • 1
Christina
  • 19
  • 5
  • Those are different methods: the first one copies the same object around, and the second one creates new, potentially different objects. Moreover, only the second method accepts user input. – ForceBru Apr 15 '17 at 12:35
  • This is why I wasn't 'happy' with the first method and created the second, but I am not a good programmer yet and I created them by my self, I do not know if this is the right way to do it – Christina Apr 15 '17 at 12:40
  • Both are fine. If you want to improve the second one a bit, consider using emplace_back to avoid copying the object every time: `boxes.emplace_back(x, y);` – ehudt Apr 15 '17 at 12:42
  • You should avoid doing what the linked top answer does. Raw owning pointers and `new` are to be avoided and attempt to solve a problem you don't even have. – nwp Apr 15 '17 at 12:44

1 Answers1

0

an Object Factory is the main part of the time, used to make different object from user input.

Imagine you have a class named Animal. And you have 3 child classes : Cat, Dog and Fish. These classes as I said all inherits from Animal. You want to create a Cat, a Dog or a Fish, to depend on user input. In this case an Object Factory is really useful; in your case it's not because you always instantiate a Box Object

the way you do it, is good. You don't need at that time something more complex like an object factory.

RomMer
  • 909
  • 1
  • 8
  • 19