** Sorry for the confusion regarding numCars in the original post. I modified the code to be consistent with the original ****
The following academic program is a simplified version of the original problem but it focuses on the issue that I have yet to resolve. There are 2 classes and a main method to this problem and the 2 classes consist of a Dealer class and a Car class. The Dealer class has a private Car* pointer that is initialized to a dynamic array in the Dealer's constructor. The error occurs in the main method when the Dealer's addCar method is invoked. In the main method I intentionally pass the Dealer variable to the addCar(Dealer& d) method to mimic the structure of the original application. The addCar method then invokes the Dealer's addCar(const Car& car) method where the access violation occurs when I execute cars[numCars++]=car; Can you explain why cars[numCars++]=car results in an access violation
/**********************************Dealer.h**************************/
#include <cstdlib>
#include "Car.h"
using namespace std;
class Dealer
{
public:
Dealer(int maxCars = DEFAULT_MAX_CARS)
:numCars(0) {cars = new Car[maxCars];}
~Dealer(){delete [] cars;}
int getTotalCars() const { return numCars;}
void addCar(const Car& car)
{
cars[numCars++] = car; // Access Violation
}
Car* begin(){return cars;};
Car* end(){ return cars + numCars;}
setNumCars(int count){numCars = count;}
private:
static const int DEFAULT_MAX_CARS = 10;
Car* cars;
int numCars;
};
/**********************************Car.h**********************/
#include <cstdlib>
#include <string>
using namespace std;
class Car{
public:
Car()
: year(0), make(""), model("")
{}
Car(int year, string make, string model)
: year(year), make(make), model(model)
{}
string getMake() const {return make;}
void setMake(string make){this->make=make;}
string getModel() const {return model;}
void setModel(string model){this->model=model;}
int getYear() const {return year;}
void setYear(int year){this->year=year;}
private:
int year;
string make;
string model;
};
ostream& operator<< (ostream& out, const Car& car)
{
out << car.getYear() << " " << car.getMake() << " " << car.getModel();
return out;
}
/**********************************Main.cpp**********************/
#include <cstdlib>
#include <iostream>
#include "Dealer.h"
using namespace std;
void addCar(Dealer& d);
int main(int argc, char *argv[])
{
Dealer d;
addCar(d);
system("PAUSE");
return EXIT_SUCCESS;
}
void addCar(Dealer& d)
{
d = Dealer();
d.addCar(Car(2007, "Honda", "Civic"));
cout << d.getTotalCars() << " total cars" << endl;
}