diff --git a/lectures/04_classes_II/README.md b/lectures/04_classes_II/README.md index 93d9b08..c578019 100644 --- a/lectures/04_classes_II/README.md +++ b/lectures/04_classes_II/README.md @@ -73,8 +73,44 @@ will sort Date objects into chronological order. - Can you solve leetcode problem 905 with an overloaded operator <, and make this overloaded operator < a member function? - Can you solve leetcode problem 905 with an overloaded operator <, and make this overloaded operator < a member function, plus make the definition of this member function outside of the class definition? --> +## 4.1 Member Initializer List in C++ -## 4.1 Copy Constructor +A **member initializer list** is a special syntax in C++ that allows class members to be initialized directly before the constructor body executes. It is used in the constructor definition, right after the parameter list and before the body of the constructor. + +### Syntax +```cpp +ClassName(parameter_list) : member1(value1), member2(value2), ... { + // Constructor body (optional, can be empty) +} +``` + +### Example + +```cpp +#include +#include + +class MyClass { +private: + std::string name; + +public: + // Constructor with member initializer list + MyClass(const std::string& initName) : name(initName) {} + + void display() const { + std::cout << "Name: " << name << std::endl; + } +}; + +int main() { + MyClass obj("Alice"); + obj.display(); // Output: Name: Alice + return 0; +} +``` + +## 4.2 Copy Constructor - A copy constructor is a constructor which is used to create a new object as a copy of an existing object of the same class. @@ -119,7 +155,7 @@ int main() { } ``` -## 4.2 Assignment Operator +## 4.3 Assignment Operator - The assignment operator (=) is used to copy the values from one object to another after both objects have been created. @@ -195,7 +231,7 @@ A = B; These two lines will: the first line creates the object A, and the second line invokes the assignment operator. -## 4.3 Destructor (the “constructor with a tilde/twiddle”) +## 4.4 Destructor (the “constructor with a tilde/twiddle”) A **destructor** is a special member function automatically called when an object goes out of scope or is explicitly deleted.