Special Members

Hello everyone! 👋

🤯🤯 Have you ever found yourself wondering why a particular object is calling a special member function that you didn't intend it to call? If so, don't worry! In this post, I will explain the 𝐬𝐢𝐱 𝐬𝐩𝐞𝐜𝐢𝐚𝐥 𝐦𝐞𝐦𝐛𝐞𝐫 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 𝐢𝐧 𝐂++, when they are called, and how understanding them can help you write better and more efficient code.

✅ The six special member functions in C++ are the 𝐝𝐞𝐟𝐚𝐮𝐥𝐭 𝐜𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫, 𝐝𝐞𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫, 𝐜𝐨𝐩𝐲 𝐜𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫, 𝐜𝐨𝐩𝐲 𝐚𝐬𝐬𝐢𝐠𝐧𝐦𝐞𝐧𝐭 𝐨𝐩𝐞𝐫𝐚𝐭𝐨𝐫, 𝐦𝐨𝐯𝐞 𝐜𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫, 𝐚𝐧𝐝 𝐦𝐨𝐯𝐞 𝐚𝐬𝐬𝐢𝐠𝐧𝐦𝐞𝐧𝐭 𝐨𝐩𝐞𝐫𝐚𝐭𝐨𝐫. Each of these functions serves a specific purpose and is automatically called by the compiler under certain circumstances.

1️⃣ The 𝐝𝐞𝐟𝐚𝐮𝐥𝐭 𝐜𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 is called when an object is declared without any arguments. It initializes the object's member variables to their default values. If no default constructor is defined explicitly, the compiler generates one automatically.

2️⃣ The 𝐝𝐞𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫, on the other hand, is called when the lifetime of an object ends. It releases any resources held by the object, such as memory allocation or file handles. If no destructor is defined explicitly, the compiler generates one by default.

3️⃣ - 4️⃣ The 𝐜𝐨𝐩𝐲 𝐜𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 and 𝐜𝐨𝐩𝐲 𝐚𝐬𝐬𝐢𝐠𝐧𝐦𝐞𝐧𝐭 𝐨𝐩𝐞𝐫𝐚𝐭𝐨𝐫 are used to create and assign new objects from existing objects. The copy constructor takes a reference to a constant object of the same class type and creates a new object with the same values as the referenced object. The copy assignment operator is used to assign an existing object's values to another object of the same type.

5️⃣ - 6️⃣ The 𝐦𝐨𝐯𝐞 𝐜𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 and 𝐦𝐨𝐯𝐞 𝐚𝐬𝐬𝐢𝐠𝐧𝐦𝐞𝐧𝐭 𝐨𝐩𝐞𝐫𝐚𝐭𝐨𝐫 are similar to their copy counterparts, but they transfer the resources from one object to another instead of copying them. This is particularly useful when dealing with large objects or when performance is critical. Understanding when each of these two special member functions is called can help you avoid unnecessary object copying.

😎 In the future, I will try to upload one post per type of special member explaining deeper details about them, such as when they are called implicitly.

I hope this post has helped you understand the importance of these special member functions and how they work. If you have any questions or want to contribute, feel free to do so! ✍️✍️✍️

Thank you for reading! 😁😁