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

后端 未结 4 639
我寻月下人不归
我寻月下人不归 2021-02-13 02:28

Given the following code:

#pragma once

class B
{
public:

    B(void)
    {
    }

    ~B(void)
    {
    }
};

I know I can also write this:

相关标签:
4条回答
  • 2021-02-13 02:39

    I just wanted to add that when you use void after the parameters like function():void it is used to indicate that the function does not return a value.

    0 讨论(0)
  • 2021-02-13 02:47

    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?

    0 讨论(0)
  • 2021-02-13 02:52

    afaik if you pass void into the constructor or any function as the argument it means that the function dosnt take any argument so example a and b are equal. but i am not sure if any of them change the function signature in any way or make it run faster etc.

    0 讨论(0)
  • 2021-02-13 02:59

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

    0 讨论(0)
提交回复
热议问题