Write a C++ program in which you are required to define a class named Citizen…

Question:

Write a C++ program in which you are required to define a class named Citizen. The class must include the following two data members.
Name
Nationality
Your Program should define three constructors for the class Citizen
a constructor with no parameter
a copy constructor
All of these constructors are meant to initialize their respective objects. In the case of the copy constructor, you are required to assign a separate space for the data members of the new object while copying the values of the previously existed object. Declare two objects (1 for each type of constructor) in main.
Write a function in class Citizen to display the initialized data members for each object.
Also, write destructor for the class Citizen. Display a message that says “destructor called” in the destructor body.

Answer:

#include <iostream>

using namespace std;

class Citizen
{
string name;
string nationality;
  
public:
  
//Constructor - 1
//without any paramaters
Citizen()
{
name="";
nationality="";
}
  
//Constructor - 2
//With paramaters
Citizen(string n, string na)
{
name=n;
nationality=na;
}
  
Citizen(const Citizen &c)
{
name=c.name;
nationality=c.nationality;
}
  
void display()
{
cout<<"Name : "<<name<<endl;
cout<<"Nationality : "<<nationality<<endl;
}
  
  
//destructor
~Citizen()
{
cout<<"destructor called"<<endl;
}
  
};

int main()
{
Citizen a; // Constructor-1 Invoked
a.display();
  
Citizen b("Rohit", "Indian"); // Constructor-2 Invoked
b.display();
  
Citizen c(b); //Constructor-3 Invoked
c.display();
return 0;
}

Leave a Comment

Your email address will not be published. Required fields are marked *