I was programming a very simple class, but while creating it I ran into a couple of question marks. In particular, question marks concerning the assigment operator (=) and the copy constructor.
For the examples I am going to give, I'll use the following class definition:
A& operator= (A&);
My class allocates some memory dynamically, so I have to implement my own copy constructor, to make sure that each instance uses a private bit of memory. Then I realised that I should probably implement operator= as well.
And about here and now I started getting confused.
Question 1: Am I correct in assuming the copy constructor is only used when explicitly writing:
Question 2: When using the following code:
a1 = a2;
This would cause the default operator= to be called, if I did not supply my own implementation? In other words, it would never call anything else but an operator= (in particular, never the copy-constructor?).
Question 3: Implementing both the operator=, A(A&) and ~A() results in a lot of double code.
(*) operator= and ~A() both need to clean up the allocated memory
(*) operator= and A(A&) both copy the members of the A& instance
I turned these blocks of code into private methods, so as to have the code centralized as much as possible. To elaborate with a piece of code:
A& operator= (A& a)
Where freeMemory and fromObject are private methods of A.
The question (finally): Is this a decent way of programming? Should I redesign something?
Or is there some other method, which leads me to Question 4
Question 4: Is there a way, rather than creating new private methods like freeMemory and fromObject, to call the Destructor for the clean-up and copy-constructor for the initialization? Exempli gratia:
A& A::operator= (A& a)
~A(); //Call destructor
A(a); //Call copy-constructor
(Or something in the neighbourhood)
Well, I've bored enough people already with this lenghty post.
Thanks to anyone who bore with me till this line, and I appreciate the others who didn't make it here for trying
The way I see it... Well, it's all pretty blurry