I have two questions.
1) What does a constructor really do? What happens if we don’t use constructors while declaring an instance?
2) Can you tell me the difference between these two?
A a(1,2)
A *a = new A(1,2)
Best regards.
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.
A constructor initializes the member variables of the class so that it is ready for use. The result of not using a constructor when declaring an instance varies on context.
If you are allocating a variable on the heap, like so:
awill point to a random address in memory until it is assigned to NULL or 0, or an existing or new instance of a class, e.g.:If you are allocating a variable on the stack, the following syntax is used:
Both of the above call the constructor of class
A, allocating an instance of it on the stack. So, that answers both your questions – your first example allocates an instance ofAon the stack, and the second allocates an instance ofAon the heap.