I have a problem with Overloading operator 'new' in my class.
Code:
time.h
#ifndef TIME_H_
#define TIME_H_
#include <cstddef>
#include <stdlib.h>
class Time {
private:
int hours;
int minutes;
public:
Time(int a = 0, int b = 0) : hours(a), minutes(b) {};
void AddMin(int m);
void AddHours(int h);
void Reset(int h = 0, int m = 0);
void Show() const;
Time Suma(const Time & t) const;
//przeladowania
void* operator new(size_t);
};
#endif
time.cpp
#include "time.h"
#include <iostream>
#include <cstddef>
#include <stdlib.h>
void Time::AddMin(int m)
{
this->minutes += m;
this->hours += this->minutes / 60;
this->minutes += this->minutes % 60;
}
void Time::AddHours(int h)
{
this->hours += h;
}
void Time::Reset(int h, int m)
{
this->hours = h;
this->minutes = m;
}
void Time::Show() const
{
std::cout << this->hours << " hours and " << this->minutes << " minutes" << std::endl;
}
////overloading
void* Time::operator new(size_t size)
{
void *storage = malloc(size);
if (NULL == storage) {
throw "allocation fail : no free memory";
}
std::cout << storage << std::endl;
Time * time = (Time*)storage;
time->minutes = 12;
return time;
}
prog.cpp
#include <iostream>
#include "time.h"
int main()
{
Time * timeNew = new Time();
timeNew->Show();
std::cout << timeNew << std::endl;
return 0;
}
And results - addreses:
0104F5E8
0 hours and 0 minutes
0104F5E8
I don't understand why my objects have other adresses in memory. I think if I return pointer, so my object timeNew(in prog.cpp) should have the same adress as storage in time.cpp.
I konw it's a function, but I used pointer, so it shouldn't delete after return to program.
Why timeNew has 0 hours and 0 minutes? I sign value in function.
Could you explain me what I do wrong?