Hi
I was playing with the new operator overload that I have learned, the typecast operator. I made a little code that implements a specified behavior:
1) A manager is responsible for an object.
2) When needed, the manager assing a temporary employee to work on the object.
3) After the job is done, the employee is dismissed.
4) At the same time, the modified object is used for other activities
I noticed that, playing with the typecast operator I can return an operator from a function, so it will be destroyed automatically, and cast the operator to the object, so I can use it later. I know that this implementation is not good. I just want to know if this behavior is correct, if it is unsafe, compiler dependant, among others...
You can see the code here or by downloading the example.
Thanks for any help!
Edit: please, see program output to betetr understand what I mean
Code:
class Box {
public:
Box () {
thisId = ++id;
cout << "Box " << thisId << " is now packed." << endl;
}
string getStatus () {
char message[60];
sprintf(message, "Box %d is now being assigned", thisId);
return message;
}
~Box () {
cout << "Box " << thisId << " is now destroyed." << endl;
}
private:
static int id;
int thisId;
};
int Box::id = 0;
template<class T>
class Operator {
public:
Operator (T& obj)
: object(obj) {
object = obj;
// do something to object
}
operator T* () {
return &object;
}
~Operator() {
//write some log
cout << "Operator dismissed." << endl;
}
private:
T& object;
};
template<class T>
class Manager {
public:
Manager(T& obj)
: object(obj) {
object = obj;
cout << "Manager is now leading." << endl;
}
T* getAnObject() {
return (T*) Operator<T>(object);
}
private:
T& object;
};
int main() {
Box box;
Manager<Box> manager( box );
string status = manager.getAnObject()->getStatus();
cout << status << endl;
// cin.get();
return 0;
}