Delete, Default and Delegating Constructors
If you using modern C++ in your programing life there are three important concepts in your life to manage methods.
If you compose a class without writing your own constructor (or copy constructor), The compiler creates a method for you to overcome basic structures. Of course, it does nothing but it is really necessary.
The thing about a scenario that you overwrite constructor method but this method takes a parameter, What happens if you did not present a constructor without parameter? Of course, the answer is the cosplayer don’t produce any constructor for you. So the default parameter cames here to help to say the compiler to generate a method for you. On the other hand, the delete keywords tells the compiler not to provide any peace of code for us for the method. Let see it in bellow.
1 2 3 4 5 6 7 8 |
class MyClass { public: // this is the code to tell compiler to generate a code for us MyClass() = default; MyClass(int initvalue); // do not add a coppy cappaility for that class MyClass(const MyClass& refObject) = delete; }; |
In some cases, you do not prefer to implement all of the version of constructors because another version may overcome that problem. So the way is delegating the method to another.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class MyClass { private: int x,y,z; public: // this is the code to tell compiler to generate a code for us MyClass() { x = 10; y = 15; z = 20; } //delegate method and //first sets x = 10, y= 15 and z = 20 //then set x from parameter MyClass(int newx) : MyClass(){ this->x = newx; } //delegate method to MyClass(newx) //MyClass(newx) will delegate it to MyClass() //sets x = 10, y= 15 and z = 20 //then MyClass(newx) set the x from paramaten then //this method will set the y from paramater MyClass(int newx, int newy) : MyClass(newx){ this->y = newy; } }; |
Keep in mind, delegation works before your codes in the method.
1 Response
[…] Delete unused constructors with delete keyword. […]