c++ - When to use a copy constructor? -
i have created class, has constructor takes parameter. right in thinking need copy constructor here?
i have class, not take pointers:
class xyz : public node { public: xyz( uint8_t node); xyz(const xyz& cxyz); ~xyz(); private: uint8_t m_node; uint16_t m_gainxyz;
and base:
class node { public: node(); virtual ~node(); protected: std::string m_name;
and when this:
xyz xyz = initxyz(node);
the compiler tells me make copy constructor.
where:
xyz pd::initxyz(source& inputnode) { if (inputnode.getnodenumber() > 10 ) { xyz element(inputnode.getnodenumber()); element.setinputnode(inputnode); return element; } else { std::cout << "error in xyz configuration" << std::endl; //throw exception; } }
but according have read on web:
if object has no pointers dynamically allocated memory, shallow copy sufficient. therefore default copy constructor, default assignment operator, , default destructor ok , don't need write own.
http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html
is true must have 1 if use constructor parameters?
i have created class, has constructor takes parameter. right in thinking need copy constructor here?
you do not need provide copy constructor classes. compiler generated ones sufficient.
here a working example based on code:
#include <iostream> #include <string> #include <stdint.h> class node { public: node() {} virtual ~node() {} protected: std::string m_name; }; class xyz : public node { public: xyz( uint8_t node) {} private: uint8_t m_node; uint16_t m_gainxyz; }; xyz initxyz(node) { return xyz(42); } int main() { node node; xyz xyz = initxyz(node); }
Comments
Post a Comment