Last active
April 10, 2020 10:53
-
-
Save webber2408/e6864344b8d5df19ea81b43e8fbc6611 to your computer and use it in GitHub Desktop.
Constructor, Destructor and this keyword
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
class Country{ | |
public: | |
string name; | |
int populationCount; | |
//Constructor | |
Country(){ | |
cout<<"Country constructor envoked"<<endl; | |
} | |
//Destructor | |
~Country(); | |
//Parameterized Counstructor | |
Country(string s, int n){ | |
this->name = s; // or name = s | |
populationCount = n; // or this->populationCount = n | |
} | |
void storeCountryInformation(string s, int n){ | |
name = s; | |
populationCount = n; | |
} | |
void printCountryDetails(){ | |
cout<<"Country Name: "<<this->name<<endl; | |
cout<<"Population Count: "<<this->populationCount<<endl; | |
} | |
}; | |
Country::~Country(){ | |
cout<<"Destructor envoked"<<endl; | |
} | |
int main(){ | |
Country c1; | |
c1.storeCountryInformation("India", 1300000000); | |
c1.printCountryDetails(); | |
Country c2 = Country("USA", 327200000); | |
c2.printCountryDetails(); | |
return 0; | |
} | |
/* | |
Output: | |
Country constructor envoked | |
Country Name: India | |
Population Count: 1300000000 | |
Country Name: USA | |
Population Count: 327200000 | |
Destructor envoked | |
Destructor envoked | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment