I'm trying to learn c++, I've read a lot about it and get it, but every time I program something that uses OOP concepts I have memory problems.
This is the exeption I'm getting with my code:
First-chance exception at 0x002EFB60 in Mathmatician.exe: 0xC0000005: Access violation executing location 0x002EFB60.
If there is a handler for this exception, the program may be safely continued.
So my question here is: what is wrong with my specific code? And more importantly, how can I avoid such exeptions? Are ther rules of thumb in c++ to avoid these?
And another thing: How can I avoid returning a local variable from a function that gets deleted (I assume just return the value itself, not a pointer?)
(More info:This specific code will be used to calculate derivative, with diffrent formulas like devision, multiplication, and more inhereting from the Form virtual class)
// Mathmatician.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <typeinfo>
#include <iostream>
using namespace std;
#include <sstream>
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
class Form {
public:
virtual Form& Derive() = 0;
Form& operator+(Form& const other);
Form& operator*(Form& const other);
virtual string Print() = 0;
};
class Number : public Form {
public:
int a;
Number(int a) : a(a)
{}
Form& Derive()
{
return (Form&) Number(0);
}
string Print()
{
return NumberToString(a);
}
};
class Addition : public Form {
private:
Form& a;
Form& b;
public:
Addition(Form& const a, Form& const b) : a(a),b(b)
{
}
Form& Derive()
{
return a.Derive() + b.Derive();
}
string Print()
{
return "("+a.Print();// + "+" + b.Print()+")";
};
};
class Multiply : public Form {
private:
Form& a;
Form& b;
public:
Multiply(Form& a, Form& b) : a(a),b(b)
{
}
Form& Derive()
{
return *new Addition(a.Derive(),b.Derive());
//return a.Derive()*b + b.Derive()*a;
}
string Print()
{
return "("+a.Print() + "*" + b.Print()+")";
};
};
inline Form& Form::operator+(Form& const other) // copy assignment
{
return Addition(*this,other);
//LocationNode* A = new LocationNode('A',1,2);
}
inline Form& Form::operator*(Form& const other) // copy assignment
{
return Multiply(*this,other);
}
int _tmain(int argc, _TCHAR* argv[])
{
Form* n = &(*new Addition((Form&)*new Number(5),(Form&)*new Number(5))).Derive();
cout << (*n).Derive().Print() << "/n";
return 0;
}
Thank you!