1#include <iostream>
2class Entity {
3
4public:
5 float x, y;
6 Entity() {
7 x = 0.0f;
8 y = 0.0f;
9 // the above is not a good practice ,instead you can use constructor member initializer list to initialize variables
10 std::cout << "Created Entity" << std::endl;
11 std::cout << "x " << x << " y " << y << std::endl;
12 //This is a constructor and it gets called everytime we instantiate an object
13
14 }
15 ~Entity() {
16 //This is a destructor object it gets called every time object is destroyed or its scope ends
17 //Note1:that this function can never return anything
18 //Note2:Followed by this ~ symbol the name of the function must be equal to class name
19 std::cout << "[Destroyed Entity]" << std::endl;
20 }
21};
22
23int main(){
24 {
25 Entity e1;
26 //here constructor is called and output => Created Entity
27 //here constructor is called and output => 0,0
28 }
29 //here Destructor is called and output => Destroyed Entity
30 // Destructor will get called here when compiler will get out of the end bracket and the lifetime of object ends
31 // have a graeater look in debug mode
32 std::cin.get();
33}
1#include <iostream>
2using namespace std;
3class HelloWorld{
4public:
5 //Constructor
6 HelloWorld(){
7 cout<<"Constructor is called"<<endl;
8 }
9 //Destructor
10 ~HelloWorld(){
11 cout<<"Destructor is called"<<endl;
12 }
13 //Member function
14 void display(){
15 cout<<"Hello World!"<<endl;
16 }
17};
18int main(){
19 //Object created
20 HelloWorld obj;
21 //Member function called
22 obj.display();
23 return 0;
24}
1class A
2{
3 // constructor
4 A()
5 {
6 cout << "Constructor called";
7 }
8
9 // destructor
10 ~A()
11 {
12 cout << "Destructor called";
13 }
14};
15
16int main()
17{
18 A obj1; // Constructor Called
19 int x = 1
20 if(x)
21 {
22 A obj2; // Constructor Called
23 } // Destructor Called for obj2
24} // Destructor called for obj1
25
1class Line {
2 public:
3 Line(); // This is the constructor declaration
4 ~Line(); // This is the destructor: declaration
5};