Difference between creating object with () or without
The other answers correctly state that the parentheses version is actually a function declaration. To understand it intuitively, suppose you wrote MainGUIWindow f();
Looks more like a function, doesn't it? :)
The more interesting question is what is the difference between
MainGUIWindow* p = new MainGUIWindow;
and
MainGUIWindow* p = new MainGUIWindow();
The version with parentheses is called value-initialization, whereas the version without is called default-initialization. For non-POD classes there is no difference between the two. For POD-structs, however, value-initialization involves setting all members to 0,
my2c
Addition: In general, if some syntactic construct can be interpreted both as a declaration and something else, the compiler always resolves the ambiguity in favor of the declaration.
Creating an object: with or without `new`
Both do different things.
The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }
) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;
The second creates an object with dynamic storage duration and allows two things:
Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword
delete
;Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)
Neither is preferred; it depends on what you're doing as to which is most appropriate.
Use the former unless you need to use the latter.
Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.
Good luck.
Your original code is broken, as it delete
s a char
array that it did not new
. In fact, nothing new
d the C-style string; it came from a string literal. delete
ing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).
Usually an object should not have the responsibility of delete
ing anything that it didn't itself new
. This behaviour should be well-documented. In this case, the rule is being completely broken.
Difference between declaring a C++ object with/without braces
Test obj();
declares a function named obj
that takes no parameters and returns an object of type Test
. It does not create an object obj
of type Test
with the default constructor.
difference between creating an object and instantiating an object
Creating an Object and instantiating an Object is the same thing
Instancing a class - difference between with and without brackets
a
is the class itself -- In python, classes are first class objects1. You can pass them around as parameters, alias them to different names (as you've done in your example) and then you can instances from any reference that you have in the current namespace.
a = myClass # a and myClass identical at this point. The interpretter won't care which you use.
a_instance = a() # instance of myClass
def make_instance(cls):
return cls()
another_instance = make_instance(a)
yet_another_instance = make_instance(myClass)
You see, python doesn't have any "compile time checking" because really -- there is no compile time. Python code gets interpreted at runtime. True, you can have SyntaxError
s pop up at when you import something, but that is still during runtime.
1No pun intended
What is difference between initializing object with new and without new
Well, the second form is illegal, unless a conversion operator has been defined.
To implement this conversion operator, you will have to use new MyClass
to construct a new instance.
So provided the second form is legal at all, the method and end result is the same.
Example of conversion operator:
public class MyClass
{
public static implicit operator MyClass(string s)
{
return new MyClass();
}
}
Note that this conversion operator also handles this line:
a = "something";
Which simply overwrites the original reference stored in a
with the new one returned by the conversion operator.
A conversion operator defines a static method named op_Implicit
(in this case) that will be called, so your code really looks like this under the hood:
MyClass a = new MyClass();
a = MyClass.op_Implicit("something");
or this:
MyClass a = MyClass.op_Implicit("something");
You can verify this using LINQPad if you can read IL.
This code:
void Main()
{
MyClass a = "something";
a = "xyz";
}
Translates to this IL:
IL_0000: nop
IL_0001: ldstr "something"
IL_0006: call UserQuery+MyClass.op_Implicit
IL_000B: stloc.0 // a
IL_000C: ldstr "xyz"
IL_0011: call UserQuery+MyClass.op_Implicit
IL_0016: stloc.0 // a
IL_0017: ret
Note the two calls to op_Implicit
.
Now, if you don't implement the conversion operator then:
MyClass a = new MyClass();
a = "something" // error
MyClass a = "something"; // error
The error message will in both cases be:
CS0029
Cannot implicitly convert type 'string' to 'MyClass'
C++ Is there a difference between creating obj with new keyword and creating directly
Yes, it is. The first one creates an object on the stack and return its address. When the function returns the stack unwinds and the object gets destroyed. Therefore the caller ends up with a dangling pointer.
The second allocates an object on the heap and returns the address. The object is valid and will continue to be so until the caller explicitly deletes it.
You should never do the first approach!
Related Topics
Is Circumventing a Class' Constructor Legal or Does It Result in Undefined Behaviour
How to Check Whether Multiple Variables Are Equal to the Same Value
How to (Un)Escape Strings in C/C++
Cyclic Dependency Between Header Files
Std::Thread Is Not a Member of Namespace Std Using Eclipse Kepler Mingw
C++ Method Only Visible When Object Cast to Base Class
Any Solution to Unpack a Vector to Function Arguments in C++
Write Concurrently Vector<Bool>
In C++ What Causes an Assignment to Evaluate as True or False When Used in a Control Structure
How to Avoid Static Member Function When Using Gsl with C++
Why Is #Define Bad and What Is the Proper Substitute
Order of Constructor Call in Virtual Inheritance
Unresolved Externals in C++ When Using Vectors and Find
Why Callback Functions Needs to Be Static When Declared in Class
Lcov/Gcov Branch Coverage with C++ Producing Branches All Over the Place