Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of having void in the constructor definition?

Tags:

c++

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?

like image 249
REA_ANDREW Avatar asked Mar 28 '09 22:03

REA_ANDREW


People also ask

What is void constructor?

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.

Can we have void in constructor?

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.

Why is constructor void?

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.

Does a constructor have a void return type?

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.


2 Answers

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?

like image 146
dirkgently Avatar answered Oct 11 '22 12:10

dirkgently


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... :-)

like image 37
TofuBeer Avatar answered Oct 11 '22 12:10

TofuBeer