Have I understood some OOP concepts correctly?

Like if I would want to store a bunch of objects somewhere would I do it somehow like

1
2
3
4
5
6
class Object {
public:
bool Instanced;
std::string Name;
Object(bool inst) : Instanced(inst) {}
}


And then the array

Object * objects = new Object[100];

And now it would use 100*sizeof(Object) bytes?
And if I would want to instance something I would just loop through the table and check if the Instanced value would be false and then switch it to true.
And to free the slot I'd just turn the value false.

Or is there some way to reserve space for instances so that it wouldn't use the space until I call the constructor?
if I would want to store a bunch of objects
then you would write std::vector<Object> objects(100, true);

is there some way to reserve space for instances so that it wouldn't use the space until I call the constructor
1
2
std::vector<Object> objects;
objects.reserve(100);
Last edited on
But it does takes the space of the structure, it's just that the objects are not constructed yet.
Read this:
http://www.cplusplus.com/reference/stl/vector/


Example of storing strings and overloaded [ ] operator


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Object {
public:
   // default constructor
   Object() { }

   // constructor taking a single string
   Object(string str)
   {
       strVec.push_back(str);
   }

   // constructor takes an array of strings and inserts them at the front	
   Object(const string* strArr, int size)
   {
	   std::vector<string>::iterator it;

       strVec.insert(strVec.begin(), strArr, strArr + size);
   }
  	
   // modifiable index operator
   string& operator[ ] (int index)
   {
  		if (0 < index < strVec.size())
             return strVec[index];
        else
     		cout << "Out of bounds!";
   }

   // non-modifiable operator - read only access
   const string operator[ ](int index) const
   {
        if (0 < index < strVec.size())
             return strVec[index];
        else
             cout << "Out of bounds!";
   }
private:
    std::vector<string> strVec;
};



Last edited on
Topic archived. No new replies allowed.