dimanche 25 janvier 2015

C++: simple quest., destructors being called multiple times

I am learning how to do OOP in c++. Please take a look at my simple example, and tell me if my OOP approach is incorrect.


I am looking to do this: create a "settings" type class that will be passed into a few other classes by reference. In the example this is the "ECU" class. I am using member initialization to pass the ECU class into each class. Is this the right way to do it?


Destructors in each class will delete any arrays created with the new command. In my code, the destructors for ECU are being called multiple times. If I had a "myArray" in ECU, and was using "delete[] myArray" in the ECU destructor, I would get errors. What's the right way to do this?


Also, the transmission and engine destructors are called before the program quits. Is this because the compiler knows they will not be used again?



// class_test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;


class ECU
{
public:
ECU()
{
cout << "ECU Constructor" << endl;
}
~ECU()
{
cout << "ECU Destructor" << endl;
}

void flash()
{
softwareVersion = 12;
}

int pullCode()
{
return softwareVersion;
}

private:
int softwareVersion;
};

class Engine
{
public:
Engine(ECU &e) : ecu(e)
{
horsepower = 76;
cout << "Engine Constructor" << endl;
}
~Engine()
{
cout << "Engine Destructor" << endl;
}

private:
ECU ecu;
int horsepower;
};

class Transmission
{
public:
Transmission(ECU &e) : ecu(e)
{
cout << "Transmission Constructor" << endl;
gearRatios = new double[6];
if (ecu.pullCode() == 12){
for (int i = 0; i < 6; i++)
gearRatios[i] = i+1.025;
cout << "gear ratios set to v12.0" << endl;
}
}
~Transmission()
{
delete[] gearRatios;
cout << "Transmission Destructor" << endl;
}

private:
ECU ecu;
double *gearRatios;
};

class Car
{
public:
Car(ECU &e) : ecu(e)
{
cout << "Car Constructor" << endl;

Engine myEngine(ecu);
Transmission myTrans(ecu);
}
~Car()
{
cout << "Car Destructor" << endl;
}

private:
ECU ecu;
};

int _tmain(int argc, _TCHAR* argv[])
{
ECU myComputer;
myComputer.flash();
Car myCar(myComputer);
system("pause");
return 0;
}

Aucun commentaire:

Enregistrer un commentaire