How do I create a copy constructor that copies an object to the newly instantiated object?
Also, how do I use the ==
operator to compare the speed
of two Tricycle
objects?
Here is the sample code:
#include <iostream>
class Tricycle
{
private:
int* speed;
//static int speedlim;
public:
Tricycle();
// copy constructor and destructor use default
int getSpeed() const { return *speed; }
//static int getspeedlim() {return speedlim;}
void setSpeed(int newSpeed) { *speed = newSpeed; }
Tricycle operator=(const Tricycle&);
void operator++();
void operator++(int);
};
//Tricycle operator++();
//Tricycle operator++(Tricycle,int);
Tricycle::Tricycle()
{
speed = new int;
*speed = 5;
//speedlim=40;
}
Tricycle Tricycle::operator=(const Tricycle& rhs){
if (this == &rhs)
return *this;
delete speed;
//speed = new int;
//*speed = rhs.getSpeed();
return *this;
}
void Tricycle::operator++(){
(*speed)++;}
void Tricycle::operator++(int){
(*speed)++;}
int main()
{
Tricycle wichita;
//std::cout << "the speed limit is : " << Tricycle::getspeedlim();;
std::cout << "Wichita's speed : " << wichita.getSpeed() << "\n";
std::cout << "Setting Wichita's speed to 6 ...\n";
wichita.setSpeed(6);
Tricycle dallas;
std::cout << "Dallas' speed : " << dallas.getSpeed() << "\n";
std::cout << "Copying Wichita to Dallas ...\n";
wichita = dallas;
std::cout << "Dallas' speed : " << dallas.getSpeed() << "\n";
wichita.setSpeed(5);
wichita++;
std::cout << "Wichita's speed : " << wichita.getSpeed() << "\n";
wichita.setSpeed(5);
++wichita;
std::cout << "Wichita's speed : " << wichita.getSpeed() << "\n";
return 0;
}
Here is a test I tried using pre-increment and post-increment to increment the speed
. This is the answer:
Wichita's speed : 5
Setting Wichita's speed to 6 ...
Dallas' speed : 5
Copying Wichita to Dallas ...
Dallas' speed : 5
Wichita's speed : 6
Wichita's speed : 6