Is the use of new/delete appropriate here? Or any way to avoid them?
The point: class myOptions need an instance of Submarine. The Parameter are known at the time the myOptions-Construcor is called.
#include <iostream> #include <string> class Submarine { public: Submarine(std::string o) { std::cout << "create class Submarine: " << o << "\n"; } ~Submarine(){}; }; class myOptions { public: myOptions(std::string o):option(o) { std::cout << "create class myOption: " << option << "\n"; submarine = new Submarine(option); } ~myOptions() { delete submarine; } private: std::string option{}; Submarine *submarine; }; int main(void){ myOptions{"help"}; }
myOptionscontain aSubmarine *. ASubmarinewill suffice. It is usually better to initialise members of a class (whether pointers or not) in the constructor initialiser list, not in the body of constructors. There are cases (e.g.Submarineis a polymorphic base) where a pointer is needed - but a smart pointer (likestd::unique_ptr<Submarine>) is preferable to a raw pointer (Submarine *) .