adding the special constructor syntax example

This commit is contained in:
Jidong Xiao
2024-02-27 13:40:32 -05:00
parent 70ad23a4d9
commit 795b222c88
2 changed files with 66 additions and 0 deletions

View File

@@ -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 <iostream>
// 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++

View File

@@ -0,0 +1,32 @@
#include <iostream>
// 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;
}