2

Possible Duplicate:
What does a colon following a C++ constructor name do?

I'm reading a book about CUDA & I'm having trouble reading this C++ syntax. I'm not sure what to search for so that's why I'm posting here.

struct cuComplex {
    float   r;
    float   i;
    cuComplex( float a, float b ) : r(a) , i(b)  {}
}

What does the cuComplex statement do? Specifically:

cuComplex( float a, float b ) : r(a) , i(b)  {}

what is this called so I can learn about it?

Community
  • 1
  • 1
ninjaneer
  • 6,951
  • 8
  • 60
  • 104
  • If you know C++ that look the same than constructor. I guess it have the same semantic – mathk Jan 26 '11 at 08:12
  • I don't know CUDA, so I don't know if this is CUDA syntax, but this is definitely valid C++ syntax anyway :) – bdonlan Jan 26 '11 at 08:15
  • I didn't know what CUDA was before I saw this question (had heard the term, never looked into it), so I answered it in terms of pure C as the question was originally tagged. – Ed S. Jan 26 '11 at 08:16

3 Answers3

6

This is C++ syntax.

cuComplex( float a, float b )

is the constructor defined for this struct.

: r(a) , i(b)

is called member initialization. Here the local members r and i are set to the parameters a and b passed to the constructor.

The rest is an empty function implementation.

BjoernD
  • 4,720
  • 27
  • 32
1

That is C++, not C, as C structs cannot contain functions in that manner (they could contain a function pointer, but that is irrelevant to the question). That is a constructor for the type "cuComplex" that takes two floats. It initializes the two member variables 'r' and 'r' with the passed in values.

EDIT per comment: The r(a) and i(b) parts are initializing the member variables with the values of the parameters to the constructor.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
1

: r(a) , i(b) in cuComplex ctor construct memory at allocation with value between parentheses.

struct cuComplex {
    const float   r;
    const float   i;
    cuComplex( float a, float b ) : r(a) , i(b)  {} // ok 
}

struct cuComplex {
    const float   r;
    const float   i;
    cuComplex( float a, float b ) {
        r = a;
        i = b;
    } // fail because once allocated, const memory can't be modified
}
Errata
  • 640
  • 6
  • 10