diff --git a/lectures/14_stacks_queues/README.md b/lectures/14_stacks_queues/README.md index 1b71a20..05da53f 100644 --- a/lectures/14_stacks_queues/README.md +++ b/lectures/14_stacks_queues/README.md @@ -23,6 +23,40 @@ - Function Objects - STL Queue and STL Stack +## 14.0 Some Special Syntax + +The following program demonstrates some special syntax about C++ constructors. + +```cpp +#include + +// custom class definition +class MyClass { +public: + // constructor + MyClass() { + std::cout << "Constructor called" << std::endl; + } + + // destructor + ~MyClass() { + std::cout << "Destructor called" << std::endl; + } +}; + +int main() { + MyClass(); + + MyClass A; + MyClass B; + return 0; +} +``` + +What is the output of this program? + +You can compile and run the [program](constructor.cpp). + ## 14.1 Function Objects, a.k.a. Functors - In addition to the basic mathematical operators + - * / < > , another operator we can overload for our C++ diff --git a/lectures/14_stacks_queues/constructor.cpp b/lectures/14_stacks_queues/constructor.cpp new file mode 100644 index 0000000..f9685bc --- /dev/null +++ b/lectures/14_stacks_queues/constructor.cpp @@ -0,0 +1,32 @@ +#include + +// custom class definition +class MyClass { +public: + // constructor + MyClass() { + std::cout << "Constructor called" << std::endl; + } + + // destructor + ~MyClass() { + std::cout << "Destructor called" << std::endl; + } +}; + +int main() { + /* creating a temporary object using constructor syntax. + It creates a temporary object that gets destructed immediately. + Why? Because this line creates a temporary object of type MyClass using the constructor syntax, + but it does not associate the temporary object with any variable. + This temporary object is constructed and immediately destroyed in the same line of code, + as it is not stored in any variable. + This is often used when you need to perform a one-time action using a constructor without storing the object for later use. + */ + MyClass(); + + MyClass A; + MyClass B; + return 0; +} +