I'm new to heap memory and C++ copy constructors
Full code:
#include <iostream>
#include <conio.h>
using namespace std;
//---------------------------------------------------------------------------
#include <iostream>
#include <conio.h>
using namespace std;
//---------------------------------------------------------------------------
class Wheel
{
public: Wheel() : pressure(32)
{
ptrSize = new int(30);
}
Wheel(int s, int p) : pressure(p)
{
ptrSize = new int(s);
}
~Wheel() { delete ptrSize; }
void pump(int amount)
{
pressure += amount;
}
private:
int *ptrSize;
int pressure;
};
//---------------------------------------------------------------------------
class RacingCar
{
public:
RacingCar()
{
speed = 0;
for (int i = 0; i < 4; i++)
wheels[i] = new Wheel();
}
//copy constructor
RacingCar(const RacingCar &oldCar)
{
for (int i = 0; i < 4; i++)
wheels[i] = new Wheel();
speed = oldCar.speed;
}
RacingCar(int value)
{
speed = value;
for (int i = 0; i < 4; i++)
wheels[i] = new Wheel();
}
~RacingCar() { delete [] wheels; }
void accelerate(int value) { speed = speed + value; }
void print() { cout << speed; }
private:
int speed;
Wheel *wheels[4];
};
//---------------------------------------------------------------------------
int main()
{
RacingCar *ptrCar = new RacingCar(10);
RacingCar car2 = *ptrCar;
ptrCar->accelerate(60);
ptrCar->print();
//car2->accelerate(50);
car2.accelerate(40);
delete ptrCar;
getch();
return 0;
}

New Topic/Question
Reply



MultiQuote





|