1 / 3100%
//This is a C++ program that illustrates the use of constructors and destructors
#include<iostream>
using namespace std;
class Car
{
private:
string make;
string model;
string color;
string f_type;
double price;
double mileage;
public:
//This is a default constructor
Car()
{
cout<<"Default Constructor Called"<<endl;
}
//Below is a parameterized constructor
Car(string mk,string mo,string c,string f,double p,double ml)
{
cout<<"Parameterized Constructor Called "<<endl;
make=mk;
model=mo;
color=c;
f_type=f;
price=p;
mileage=ml;
}
//Below is a copy constructor
Car(Car &obj)
{
cout<<"Copy Constructor Called "<<endl;
make=obj.make;
model=obj.model;
color=obj.color;
f_type=obj.f_type;
price=obj.price;
mileage=obj.mileage;
}
void setData(string mk,string mo,string c,string f,double p,double ml)
{
make=mk;
model=mo;
color=c;
f_type=f;
price=p;
mileage=ml;
}
void displaydata()
{
cout<<"Vehicle Properties: "<<endl;
cout<<"Vehicle Make: "<<make<<" \n";
cout<<"Vehicle Model: "<<model<<endl;
cout<<"Vehicle Color: "<<color<<endl;
cout<<"Vehicle Fuel Type: "<<f_type<<endl;
cout<<"Vehicle Price: "<<price<<endl;
cout<<"Vehicle Mileage: "<<mileage<<endl<<endl;
}
~Car()
{
cout<<"Destructor Called "<<endl;
}
};
int main()
{
Car car1;//default constructor used to initialize this object
Car car2("Honda","CRV","Blue","Petrol",1300000,140000); //parameterized constructor used to
create this object
Car car3("Toyota","Fortuner","Black","Diesel",3700000,100000);//parameterized constructor
used to create this object
car1.setData("Suzuki","Escudo","Red","Petrol",1700000,110000);
car1.displaydata();
car2.displaydata();
car3.displaydata();
Car car4=car3; //Copy constructor used to initialize this object
car4.displaydata();
return 0;
}
Students also viewed