What is the member variables list after the colon in a constructor good for?

前端 未结 8 1033
予麋鹿
予麋鹿 2020-12-11 02:34

I\'m reading this C++ open source code and I came to a constructor but I don\'t get it ( basically because I don\'t know C++ :P )

I understand C and Java very well.

相关标签:
8条回答
  • 2020-12-11 03:11

    You are pretty close. The first line is the declaration. The label left of the :: is the class name and for it to be a constructor, the function name has to be the same as the class name.

    TransparentObject::TransparentObject( int w, int x, int y, int z )
    

    In C++ you can optionally put a colon and some initial values for member variables before the start of the function body. This technique must be used if you are initialzing any const variables or passing parameters to a superclass constructor.

    : 
     _someMethod( 0 ),
     _someOtherMethod( 0 ),
     _someOtherOtherMethod( 0 ),
     _someMethodX( 0 )
    

    And then comes the body of the constructor in curly braces.

    {
       int bla;
       int bla;
    }
    
    0 讨论(0)
  • 2020-12-11 03:16

    The code between the argument list and the {}s specifies the initialization of (some of) the class members.

    Initialization as opposed to assignment---they are different things---so these are all calls to constructors.

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