In c++ we can calls method of a class without instantiating it. Such as;
MyClass mc;
mc.method();
what are the advantages & disadvantages of using methods of class without instantiating it? When should we use this type?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Just because you haven’t explicitly invoked a constructor, doesn’t mean you haven’t instantiated it. The form you’ve used invokes the default constructor. This may or may not setup the class correctly, but that’s a matter for the class’s author to sort out, not the code that uses it.
EDIT: It occurs to me that the advice I gave might confuse more than it helps, so I’ll provide a couple of examples:
The following class has a trivial default constructor that doesn’t initialise its members:
You can use this class with or without an explicit constructor:
In both forms above, the class is instantiated and the instance is ready for use without causing any crashes or invoking undefined behaviour. In the case of
p, however, the member variablesxandyhaven’t been initialised, and will thus have values that are, for all intents and purposes, random. Typically, you would populate such an object by setting its member variables explicitly……or passing the object to another function to populate…
In other cases, the default constructor must initialise the object in a non-trivial way:
The purpose of the constructor is to convert raw memory into a usable object. In the case of
Point, no action is required for an instance to be usable. In the case ofMyArray,len_andcapacity_must be set to zero at construction time so that member functions likeadd()behave correctly (I also setarr_to the null pointer for good measure).The key message in all of this is that the object may or may not be initialised, but it is instantiated.