Challenge activity 8.10.1: Write a copy constructor. Write a copy constructor fo
ID: 666205 • Letter: C
Question
Challenge activity 8.10.1: Write a copy constructor.
Write a copy constructor for CarCounter that assigns origCarCounter.carCount to the constructed object's carCount. Sample output for the given program:
#include <iostream>
using namespace std;
class CarCounter {
public:
CarCounter();
CarCounter(const CarCounter& origCarCounter);
void SetCarCount(const int count) {
carCount = count;
}
int GetCarCount() const {
return carCount;
}
private:
int carCount;
};
CarCounter::CarCounter() {
carCount = 0;
return;
}
Explanation / Answer
#include <iostream>
using namespace std;
class CarCounter {
public:
CarCounter();
CarCounter(const CarCounter& origCarCounter);
void SetCarCount(const int count) {
carCount = count;
}
int GetCarCount() const {
return carCount;
}
private:
int carCount;
};
CarCounter::CarCounter() {
carCount = 0;
return;
}
CarCounter::CarCounter(const CarCounter& origCarCounter) {
carCount = origCarCounter.carCount;
return;
}
int main()
{
CarCounter c1;
cout<<"Enter the number of Cars:";
int car;
cin>>car;
c1.SetCarCount(car);
CarCounter c2=c1;
cout<<"Cars Counted:"<<c2.GetCarCount();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.