Home > Mobile >  create a class in C
create a class in C

Time:06-25

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;
    
    
}

CodePudding user response:

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>
  • Related