Basic class operators
Is it necessary to have a copy constructor, destructor and operator = in a class that only has a static data member, no pointer
class myClass{
int dm;
public:
myClass(){
dm = 1;
}
~myClass(){ } // Is this line usefull ?
myClass(const myClass& myObj){ // and that operator?
this->dm = myObj.dm;
}
myClass& operator=(const myClass& myObj){ // and that one?
if(this != &myObj){
this->dm = myObj.dm;
}
return *this;
}
};
I read that the compiler built one for us, so it is better not to have one (when we add a data item, we have to update the statements)
a source to share
If you can't think of anything for a destructor, you almost certainly don't need to define one, except for a virtual destructor in the base class. And if you don't need a destructor, you almost certainly don't need to define a copy constructor and an assignment operator, and you shouldn't, as it's easy to get it wrong.
The compiler will provide them on its own. By default, the copy / assignment constructor operator copies / assigns all members (and the base parts of the object if the class is derived) and the destructor does nothing (calls the destructor of all members / bases, but that's what you can "t even if you provide your own - this happens after the body exits the user-defined destructor).
Therefore, in this case, it is completely unnecessary. All you can achieve is inject errors into the code (for example, add another contributor, but forget to also update the copy constructor to copy it over).
myClass& operator=(const myClass& myObj){ // and that one?
if(this != &myObj){
this->dm = myObj.dm;
}
return *this;
}
I don't think you should undertake a "self-naming test" dogmatically. Does something bad happen when you assign an int to yourself (even indirectly)?
int a = 10;
int& ref = a;
a = ref;
Avoiding self-determination is only applicable if the assignment operator first destroys resources currently held and then creates new ones from the object on the right side. Then it would be a disaster to find out that you actually indirectly destroyed the right object as well.
But even so, it would be better to first create a copy of the right side and then destroy the contents of the left side, in which case self-awareness is not an issue (other than potentially ineffective) .For a good way of implementing this, google copy and share idioms.
a source to share