If I have a class Rectangle
class Rectangle{
private:
double width;
double height;
public:
void Set(double w , double l){
width = w;
height = l;
}
};
and I decleare an object such:
Rectangle *Obj;
and then try to initialize its properties:
Obj->Set(3,5);
the compiler shows at run-time: The variable 'Obj' is being used without being initialized.
The problem can be solved by:
Rectangle *Obj=new Rectangle;
I would ask about the reason! And why the compiler doesn't show any error at compiling time?
Rectangle *Obj;
just defines a pointer to an object of class Rectangle
. Defining a pointer does not reserve any memory for the object itself, just for the pointer. Thus, if you access the pointer, you will likely end up at an address in memory that doesn't even belong to your process. However, the compiler cannot know that you haven't initialized the pointer (the keyword here is aliasing) and hence cannot output an error message.
The solution is either using new
like you suggested, or declare an instance of Rectangle
like so:
Rectangle Obj;
which will call a default constructor. You can then set your members using
Obj.Set(3, 5);