Sorry my description is not a bit more detailed, but I just haven't got a clue why this is crashing. I am a complete newb (I"m just teaching myself), so hopefully one of you more experienced guys will spot the problem quickly.
The crash is occurring in the overloaded << operator function contained within road.cpp. The crash is occurring when I try and cout the variable rCar (if I comment that bit out, it doesn't crash).
Hopefully the code is fairly self-explanatory. Obviously it's nothing useful, just me trying to get my head around the language.
Thanks in advance.
main.cpp
Code:
#include <iostream>
#include "car.h"
#include "road.h"
using namespace std;
int main()
{
Car c(1962, "EK", "Holden");
cout << c << endl;
Road r("Maitland");
cout << r << endl;
cout << "Adding the car..." << endl;
r.add(&c);
cout << r << endl;
}
car.h
Code:
#ifndef CAR_H
#define CAR_H
#include <string>
#include <ostream>
using namespace std;
class Car
{
public:
const short m_nYear;
const string m_strModel;
const string m_strMake;
Car(short, string, string);
friend ostream& operator <<( ostream&, Car c );
private:
protected:
};
#endif // CAR_H
car.cpp
Code:
#include "car.h"
#include <iostream>
using namespace std;
Car::Car(short year, string model, string make) : m_nYear(year), m_strModel(model), m_strMake(make)
{
cout << "Car constructed: " << (*this) << "." << endl;
}
ostream& operator <<( ostream& outputStream, Car c )
{
outputStream << c.m_nYear << " " << c.m_strModel << " " << c.m_strMake;
return outputStream;
}
road.h
Code:
#ifndef ROAD_H
#define ROAD_H
#include "car.h"
#include <iostream>
#include <ostream>
using namespace std;
class Road
{
public:
Road( string );
~Road();
const string m_strName;
friend ostream& operator <<(ostream&, Road);
void add(Car* c);
private:
Car* m_pcCar;
};
#endif // ROAD_H
Code:
#include "road.h"
#include "car.h"
#include <iostream>
using namespace std;
Road::Road(string name) : m_strName(name)
{
cout << (*this) << " was created." << endl;
}
Road::~Road()
{
}
void Road::add(Car* pCar)
{
this->m_pcCar = pCar;
}
ostream& operator <<( ostream& outputStream, Road r )
{
Car& rCar = *(r.m_pcCar);
if (r.m_pcCar)
outputStream << r.m_strName << " road, featuring a " << rCar; // <-- causes CRASH!!!
else
outputStream << r.m_strName << " road";
return outputStream;
}