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?
In C++, we can instantiate the class object with or without using the new keyword. If the new keyword is not use, then it is like normal object. This will be stored at the stack section. This will be destroyed when the scope ends.
Bookmark this question. Show activity on this post. class Rectangle{ private: double width; double height; public: void Set(double w , double l){ width = w; height = l; } };
To create an object of a named class by using an object initializer. Begin the declaration as if you planned to use a constructor. Type the keyword With , followed by an initialization list in braces. In the initialization list, include each property that you want to initialize and assign an initial value to it.
Assigning value to a variable is called initialization of state of an object. Initialization of variable means storing data into an object. 3. We can assign the value of variables in three ways: by using constructor, reference variable, and method.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With