Given the following code:
#pragma once
class B
{
public:
B(void)
{
}
~B(void)
{
}
};
I know I can also write this:
#pragma once
class B
{
public:
B()
{
}
~B()
{
}
};
What is the purpose of having void
in the first example? Is it some type of practice that states the constructor take zero parameters?
public void class1() is not a constructor, it is a void method whose name happens to match the class name. It is never called. Instead java creates a default constructor (since you have not created one), which does nothing.
Note that the constructor name must match the class name, and it cannot have a return type (like void ). Also note that the constructor is called when the object is created.
Constructor is not like any ordinary method or function, it has no return type, thus it does not return void. Constructors don't create objects.
A constructor cannot have a return type (not even a void return type). A common source of this error is a missing semicolon between the end of a class definition and the first constructor implementation. The compiler sees the class as a definition of the return type for the constructor function, and generates C2533.
The two are same, at least in C++. In C, providing an empty pair of parentheses typically means an unspecified parameter list (as opposed to an empty parameter list). C++ does not have this problem.
How can a correct answer get downvoted so many times? Yet another SO bug?
A long time ago you did something like this in C (my pre-ISO C is rusty :) ):
void foo(a, b)
int a,
int b
{
}
while C++ was being created the name mangling required the types of the arguments, so for C++ it was changed to:
void foo(int a, int b)
{
}
and this change was brought forward to C.
At this point, I believe to avoid breaking existing C code this:
void foo()
and this:
void foo(void)
meant two very different things, ()
means do not check for the argument number or type, and (void)
means takes no arguments. For C++ ()
meaning not to check anything was not going to work so ()
and (void)
mean the same thing in C++.
So, for C++ ()
and (void)
were always the same thing.
At least that is how I remember it... :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With