c++ - How do I instantiate an array's size later? -


let's have base class called

class base { public:     std::string array[]; }; 

the size string array not decided until class extends it, what's correct syntax doing so?

eg, later on in derived class

derived::derived() {     array[] = new array[40]; } 

if want use c-style array, size must fixed , known @ compile-time. , in case, use safer, zero-overhead std::array<> wrapper instead.

if size of container not known @ compile-time, practice use std::vector (or std::deque in cases, based on requirements in terms of memory allocation) , avoid manual memory management through raw pointers, new[] , delete[]:

#include <string> // std::string #include <vector> // std::vector  class base { public:     std::vector<std::string> myvector; }; 

besides, design won't require dedicated work in constructor (and destructor) of derived. if done derived's default constructor allocate array, can avoid explicitly defining default constructor @ all, , let compiler generate 1 implicitly - same story destructor.

also, discourage using names of standard container classes (like array) names variables. myarray (or myvector, in example above) more appropriate choices.


Comments