When I run the following code in Microsoft visual studio it outputs junk values (memory addresses?) but when it is run in g++ it outputs what I intend it to (with a few changes like changing srand). How do I fix it to work in visual studio? I only have a few months coding experience and this issue has been bugging me for awhile now.
class Vehicle
{
protected:
int * vin;
double * gasMileage;
public:
Vehicle();
Vehicle(int v, double g);
virtual void display(){cout<<"vin: "<<*vin<<endl<<"gasMileage: " <<*gasMileage<<endl;}
virtual double calcGasUsed(int milesDriven){return *gasMileage * milesDriven;}
int getVin(){return *vin;}
double getGasMileage(){return *gasMileage;}
void changeVin(int newvin) {vin=&newvin;}
void changeGasMileage(double newGasMileage){gasMileage=&newGasMileage;}
void drive();
};
class Suv:public Vehicle
{
protected:
bool *fourWDStatus;
double * fourWDGasMileage;
public:
Suv();
Suv(int v, double g,bool status, double fwdg);
void display();
double calcGasUsed(Suv&, int milesDriven);
bool getFourWDStatus(){return *fourWDStatus;}
double getfourWDGasMileage(){return *fourWDGasMileage;}
void changeFourWDStatus(bool status) {fourWDStatus=&status;}
void changeFourWDGasMileage(double newGasMileage){fourWDGasMileage=&newGasMileage;}
};
Vehicle::Vehicle()
{
this->vin=0000;
this->gasMileage=00;
}
Vehicle::Vehicle(int v, double g)
{
this->vin=&v;
this->gasMileage=&g;
}
Suv::Suv(int v, double g,bool status, double fwdg)
{
this->vin=&v;
this->gasMileage=&g;
this->fourWDStatus=&status;
this->fourWDGasMileage=&fwdg;
}
Suv::Suv()
{
this->vin=0000;
this->gasMileage=00;
this->fourWDStatus=false;
this->fourWDGasMileage=00;
}
void Suv::display()
{
Vehicle::display();
cout<<"fourWDStatus: "<<*fourWDStatus<<endl<<"fourWDGasMileage: "<<*fourWDGasMileage<<endl;
}
void Vehicle::drive()
{
int r=rand()%10000;
cout<<calcGasUsed(r)<<endl;
}
double Suv::calcGasUsed(Suv&, int milesDriven)
{
double x;
if (*fourWDStatus== true)
{
x= ((*fourWDGasMileage) * (milesDriven));
return x;
}
else
{
x=((*gasMileage) * (milesDriven));
return x;
}
}
void main()
{
cout << "test";
srand(NULL);
Suv A(300,12.2,false,16.6);
Suv B(200,15.5,false,20.1);
B.changeFourWDStatus(true);
Vehicle C(111,20.5);
C.drive();
C.display();
B.display();
Vehicle arrOfCars[]={A,B,C};
A.drive();
B.drive();
C.drive();
system("pause");
}
The members
Vehicle::vin,Vehicle::gasMileageas well asSuv::fourWDStatusandSuv::fourWDGasMileageare not correctly initialized pointers.From the code you posted it seems you would be better off by changing them from pointers to regular variables (and adjusting the methods appropriately).
EDIT: If using pointers is a part of assignment, you have to initialize them correctly. This means, in your case, allocating a memory in constructors. It could be this way: