Last active
April 11, 2020 14:34
-
-
Save webber2408/6f2c3a577cae9ce2cd7a75586d5c7e26 to your computer and use it in GitHub Desktop.
User defined copy constructor
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; | |
int *stateCount; | |
Country(){ | |
stateCount = new int; //dynamically allocate memory for an integer and return it's address | |
} | |
//User defined copy constructor | |
Country(Country &c){ | |
name = c.name; | |
populationCount = c.populationCount; | |
stateCount = new int; //dynamically allocate memory for an integer and return it's address | |
*stateCount = *(c.stateCount); | |
} | |
void setCountryDetails(string s, int n, int count){ | |
this->name = s; // or name = s | |
populationCount = n; // or this->populationCount = n | |
*stateCount = count; | |
} | |
void printCountryDetails(){ | |
cout<<"Country Name: "<<this->name<<endl; | |
cout<<"Population Count: "<<this->populationCount<<endl; | |
cout<<"State Count: "<<*stateCount<<endl; | |
} | |
}; | |
int main(){ | |
Country c1; | |
c1.setCountryDetails("India", 1300000000, 28); | |
Country c2 = c1; | |
int num = 29; | |
c2.stateCount = # | |
cout<<"C2"<<endl; | |
c2.printCountryDetails(); | |
cout<<"C1"<<endl; | |
c1.printCountryDetails(); | |
} | |
/* | |
Output: | |
C2 | |
Country Name: India | |
Population Count: 1300000000 | |
State Count: 29 | |
C1 | |
Country Name: India | |
Population Count: 1300000000 | |
State Count: 28 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment