What is the Difference in between 2 statements
int main()
{
A a = new A();
A a;
}
Please explain this two object creation statements.
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.
The first command allocates a variable on the stack (
A a), and initializes on the heap (new A()).The second one only allocates the variable on the stack. It is not initialized, and therefore cannot be used until you assign it, either by a return value from a function or calling the class constructor.
There are many different reason in code you might see the declaration separated from the actual assignment.
For example, sometimes you need to declare a variable outside of a
try {} catch {}clause. Lets say your class takes a value in its constructor. You have a function that gets that data, say from a database. However, since its a DB call, you want to catch the exception, and if its thrown, initialize the class with a default value, instead of the returned value from the DB call.Due to the way scoping works in C#, variables declared inside a
try {} catch {}are not accessible outside of it, hence you would need to declare the variable earlier in code before you initialize it.