Instantiate a class with or without parentheses?
Any difference in performance is going to be absolutely negligible.
While both ways are fine, I personally would prefer using new Car();
because usually, a method is being called here, and function/method calls in PHP require ()
. Also, it's more consistent with instantiations that have parameters.
But in the end, it's down to taste. It doesn't matter which way you choose, but when you choose one, stick to it consistently!
Instantiate class with or without parentheses?
This is a quirk of C++ syntax. The line
CTest t1;
declares a local variable of type CTest
named t1
. It implicitly calls the default constructor. On the other hand, the line
CTest t2();
Is not a variable declaration, but a local prototype of a function called t2
that takes no arguments and returns a CTest
. The reason that the constructor isn't called for t2
is because there's no object being created here.
If you want to declare a local variable of object type and use the default constructor, you should omit the parentheses.
In C++11, you can alternatively say
CTest t2{};
Which does actually call the default constructor.
Hope this helps!
Why do I need parentheses when instantiating a class?
In languages where the calling of a function/method/macro takes the form
foo(param1, param2, param3)
then it is almost universally true that, if foo
were to take no parameters, the call would be
foo()
and further that, depending on the language
foo
is either incorrect, or means something else.
Now lets consider your example, expanded a bit
H1 = Human
H2 = Human
H3 = Human
In this case, nothing was called. H1
, H2
and H3
have all been assigned the same reference, which is a reference to the class Human
and not to any instance of that class.
H1 = Human()
H2 = Human()
H3 = Human()
In this case, the class was instantiated 3 times, that means that the __init__
function was run 3 sepearate times, and the result of each is a different instance of Human
. H1
, H2
and H3
now point to three different objects, all instances of Human
. Since they are instances, they have a self
.
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
Is there a difference between instantiation with parentheses or without?
The are exactly the same, you can compare opcode of these 2 scripts:
1 script:
$object1=new User();
$object1->name="Hello";
echo $object1->name;
class User {}
opcode:
line # * op fetch ext return operands
---------------------------------------------------------------------------------
3 0 > FETCH_CLASS 4 :0 'User'
1 NEW $1 :0
2 DO_FCALL_BY_NAME 0
3 ASSIGN !0, $1
4 4 ASSIGN_OBJ !0, 'name'
5 OP_DATA 'Hello'
5 6 FETCH_OBJ_R $5 !0, 'name'
7 ECHO $5
6 8 NOP
9 > RETURN 1
2 script:
$object1=new User;
$object1->name="Hello";
echo $object1->name;
class User {}
opcode:
line # * op fetch ext return operands
---------------------------------------------------------------------------------
3 0 > FETCH_CLASS 4 :0 'User'
1 NEW $1 :0
2 DO_FCALL_BY_NAME 0
3 ASSIGN !0, $1
4 4 ASSIGN_OBJ !0, 'name'
5 OP_DATA 'Hello'
5 6 FETCH_OBJ_R $5 !0, 'name'
7 ECHO $5
6 8 NOP
9 > RETURN 1
Declaring a new instance of class with or without parentheses
Both will call the default parameter-less constructor. So I believe both are same.
PHP class instantiation. To use or not to use the parentheses?
They are equivalent. If you are not coding by any code convention, use which you like better. Personally, I like to leave it out, as it is really just clutter to me.
Instantiate a Class - With or Without Parens?
I wrote a similar answer here:
https://stackoverflow.com/a/20664517/1296806
It's especially relevant that constructors are not like methods with respect to parens.
A constructor always has a non-implicit parameter list. If you omit it in the definition, then it is supplied.
new A
is idiomatic. (If there's a need to rationalize it, consider the instance as a result. If instantiation is a side effect, nothing non-primitive could be pure.)
new A().a
requires the parens, so they are useful syntactically.
You must supply parens if an implicit follows; see the link.
C++ class initialization with and without parentheses
In the first case the object is left uninitialized, while in the second case the object is guaranteed to be value-initialized, which in this case as the type is POD it means zero-initialized
Why do classes with no constructor arguments need parenthesis
Can someone please help me understand why in Python you need to instantiate a class with parenthesis even if there are no constructor arguments other than self.
The reason is simple: when you instantiate an object, you are actually calling its class (which is itself an object), and you call objects using ()
.
In python, everything is a first-class object, even classes (and functions!) themselves. In order for a class to be a first class object, it follows that the class needs its own class (metaclass) to define its behavior. We call the class of a class "metaclass" so as to avoid confusion when talking about classes and classes of classes.
To answer the second part of your question: "things" were happening when you used MainViewController
instead of MainViewController()
because MainViewController
is a full-fledged object, just like any other object.
So you might ask: what is the class - actually the metaclass - of the MainViewController
object?
As you know, you can create a class like this:
class MyClass:
pass
When you do this, you are in actuality creating a new instance of the metaclass known as type
.
Note that you can create the same class this way; there is literally no difference between the below and the above:
MyClass = type('MyClass', (object,), {})
The type
metaclass is the base metaclass of all classes. All python "new style classes" (not so "new" anymore since they were implemented in python 2.1, I believe) are of the class type
:
print(type(MyClass)) # type
print(type(list)) # type
print(type(int)) # type
# Note that above, type is being used as a "function" (it's really just a callable)
Interestingly enough, type
is even its own metaclass:
print(type(type)) # type
So to reiterate: the class MyClass
is actually an instantiation of type
. It follows, then, that calling the class results in running the __call__
method of its metaclass.
When you do:
obj = MyClass()
...you are calling MyClass
, which results (in the background) in running the method type.__call__()
.
This is the case with all user defined classes, btw; if you include the __call__
method in your class, your class is callable, and the __call__
method is executed when you call class instances:
class MyCallable():
def __call__(self):
print("You rang?")
my_instance = MyCallable()
my_instance() # You rang?
You can see this in action. If you create your own metaclass by subclassing type
, you can cause things to happen when an instance of the class based on your custom metaclass is created. For example:
class MyMeta(type):
def __call__(self, *args, **kwargs):
print "call: {} {} {}".format(self, args, kwargs)
return super().__call__(*args, **kwargs)
# Python 3:
class MyClass(metaclass = MyMeta):
pass
# Python 2:
class MyClass():
__metaclass__ = MyMeta
pass
Now when you do MyClass()
, you can see that the __call__
method of MyMeta
happens before anything else (including before __new__
AND before __init__
).
Related Topics
Best Way to Start a Thread as a Member of a C++ Class
Reference to Non-Static Member Function Must Be Called
How to Create a Thread-Safe Singleton Pattern in Windows
Why Do Type Aliases in C++ Use 'Using' Instead of 'Typedef' in Their Syntax
C++ "Named Parameter Idiom" VS. Boost::Parameter Library
Aligned_Storage and Strict Aliasing
Is Std::String Thead-Safe with Gcc 4.3
Should Accessors Return Values or Constant References
Using Pair as Key in a Map (C++/Stl)
Are Mutex Lock Functions Sufficient Without Volatile
Convert Iso-8859-1 Strings to Utf-8 in C/C++
How to Use a C++11 to Program the Arduino
Alternative to C++ Static Virtual Methods
Advice on Mocking System Calls