0

I would like to know in which situations should a copy constructor or assignment operator should be defined. From what I researhed I see that whenever value is passed by value or returned by value, the copy constructor and overloaded assignment operator needs to be defined. However, when pointers or reference are used for pass/return by pointer or reference(&), do we need copy constructor/overloaded assignment operator

class Sample { public : // Assume a constructor that sets the node member SampleNode * getNode() { return _node; } private: SampleNode * node; } class SampleNode { public: void getValue() { return _value; } private: unsigned int value; } main() { Sample * ptr = new Sample(15); SampleNode *node = getNode(); // Do we need a copy constructor here? } 
5
  • 2
    that code makes no sense. you'd get tons of compiler errors. to give a few problems: 1. new Sample(15) can't work. no appropriate constructor. 2. return _node. unidentified identifier _node. 3. getNode(); unidentified function getNode. etc. etc. Commented Oct 15, 2013 at 20:14
  • Your example technically has undefined behaviour (unless you fix it along with the compiler errors), but keep in mind the ones the compiler gives you generally work if you're doing things right. Commented Oct 15, 2013 at 20:14
  • 3
    You should learn about the rule of three Commented Oct 15, 2013 at 20:15
  • 2
    Copy constructors/assignment are used when you pass by value, not by reference. In this case, you're doing everything with pointers. A dangerous game, but one that does successfully let you avoid worrying about copy constructors. Commented Oct 15, 2013 at 20:16
  • Sorry about the code. I just came up with a sample code, just to illustrate my question. This definetly will give lot of compiler errors. @MadScienceDreams : Why do you say its a dangerous game? Please let me know if there are an hidden corner cases that I need to keep in mind whhile coding Commented Oct 15, 2013 at 20:24

1 Answer 1

2

Defining a pointer or reference to an object doesn't require the use of any constructors.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.