2

In C++ suppose I defined a class named Player without a default constructor.

When I creating a class instance in the main function:

Player John; The class will be created and I can see it in the debugger but the Player Adam() the class will not be created

Why the class will not be created in Player Adam(); isn't Adam() will trigger the default constructor which have no arugments ?

what is the difference between using () and not using them when there is not default constructor.

#include<iostream>
class Player{
   
    private:
std::string name{"Jeff"};
double balance{};


    public: 

  
};
int main()
{
     Player John; // the class will be created I can see it in the debugger
     Player Adam();//the class will not be created
    
    
    std::cout<<"Hello world"<<std::endl;
    return 0;
    
    
}
UnholySheep
  • 3,967
  • 4
  • 19
  • 24
Andrew
  • 25
  • 4
  • 2
    Does this answer your question? [Default constructor with empty brackets](https://stackoverflow.com/questions/180172/default-constructor-with-empty-brackets) – UnholySheep Jun 24 '22 at 22:29
  • 1
    `Player Adam();` is a function declaration, just like `int f();`. – Pete Becker Jun 24 '22 at 23:59
  • This particular behavior of C++ is so famously confusing that it has its own Wikipedia article: [Most vexing parse](https://en.wikipedia.org/wiki/Most_vexing_parse). – ComicSansMS Jun 25 '22 at 05:54

1 Answers1

2

I think your problem is that you are not really creating the second object. I put your code on compiler explorer here, where you can see the compilation warnings:

<source>: In function 'int main()':
<source>:16:17: warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse]
   16 |      Player Adam();//the class will not be created
      |                 ^~
<source>:16:17: note: remove parentheses to default-initialize a variable
   16 |      Player Adam();//the class will not be created
      |                 ^~
      |                 --
<source>:16:17: note: or replace parentheses with braces to value-initialize a variable
Compiler returned: 0

It looks like the compiler is interpreting Player adam(); as a function declaration and not as an object instantiation. If you change the declaration to Player adam{};, or remove the parentheses completely, the compiler will interpret this "correctly", and the problem should be solved.

Indeed, in the assembly code you can see that the object constructor, Player::Player is only called once (you need to change the optimization to -O0 to see it, otherwise it will get inlined):

main:
        push    rbp
        mov     rbp, rsp
        push    rbx
        sub     rsp, 56
        lea     rax, [rbp-64]
        mov     rdi, rax
        call    Player::Player() [complete object constructor]
        
        <printing code begins here>
Dario Petrillo
  • 980
  • 7
  • 15