adding the special constructor syntax example
This commit is contained in:
@@ -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++
|
||||
|
||||
32
lectures/14_stacks_queues/constructor.cpp
Normal file
32
lectures/14_stacks_queues/constructor.cpp
Normal 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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user