I have a code that gives wrong output. I have 3 classes, i.e., Material, Elastic and Solver. The Material is a parent class and the Elastic is derived from the Material class. My main function creates an object of Solver class and then passes a value through the SetMaterial function, which in turn creates an Elastic class object and sets values for a parameter in the Elastic class. When I try to retrieve that value through the GetValue function I get a wrong value.
Could someone please explain to me what is wrong here.
The Elastic object that you create on line 57 is a local variable that only exists for as long as the function runs, so later when Solve() is called it tries to retrieve the value from a non-existing object which will obviously not work.
Since the program is incorrect there isn't really any guarantees what will happen. This is called undefined behaviour. You might be able to figure out why things happen the way they do by looking at the assembly that the compiler generates but it's not very useful information, and the behaviour could easily change when you change compiler settings or just change some other part of the code which could trigger different optimizations to happen.
Well, I am writing a Finite Element code. So the idea is to create a parent class which can be pointed to different material classes depending on the user's input. So, like Elastic, I have 4-5 other classes which are derived from the parent Material class and I have a if-elseif statement somewhere in my code to do *mobj = & eobj . That is why I need to keep mobj in my code.