There are multiple errors in your code
&symbol
(wheresymbol
ischar[21]
) yieldschar(*)[21]
, usesymbol
directly and let it decay tochar*
or use explicitly&symbol[0]
double weight;
is uninitialized local variable, using it results in undefined behavior - you should initialize it:double weight = 0.0;
double w= 0;
used to declare a member ofclass Molecule
is invalid, you could use constructor's initializer list:Molecule() : w(0.0) { } // initializes `w` to `0.0`
s = symbol;
wheres
ischar[21]
andsymbol
ischar*
will not copy strings, for C-style copyingstrcpy
could be used (note that C and C++ are different languages)you have called
new[]
so it would be nice and appropriate to calldelete[]
as well and instead of relying on OS cleaning it up after the program terminates: (otherwise follow the point 6)Molecule *molecule = new Molecule[n]; ... delete[] molecule;
If you are allowed to use vectors, replace
Molecule *molecule = new Molecule[n];
withstd::vector<Molecule> molecules(n);
If you are allowed to use
std::string
1) objects, replacechar[21]
/char*
withstd::string
objects
Other suggestions:
use meaningful names for variables, if you want to explicitly distinguish private members from other local variables, good convention is to use
_
at the end of the name:class Molecule { private: std::string symbol_; std::string description_; double weight_;
1) Basically what you need to know about std::string
is that it is a template that wraps raw char*
and it already contains well-defined copying, concatenation using operator +
and most important: you don't need to bother with memory management. Just #include <string>