-2

I'm new to c++ and its developing. I saw a code snippt but i have no idea what it does can anyone please explain what it does. it will be helpful for undestanding about rest of the code. any help is appriated.

TrajectData::TrajectData(int numCamera)
:_max_pix_num(0) // **what is says after : symbol** 
{
    numCamera=3;

    _numCamera = ( numCamera > _MAX_IMAGE ) ? _MAX_IMAGE : numCamera;
    // **above line please explain** 
}

thank you very much.

user3423301
  • 43
  • 1
  • 6
  • Its a member initialization list. [See this answer](http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor/8523361#8523361) – WhozCraig Feb 28 '15 at 08:59
  • For the second line you ask for explanation, take a look at http://stackoverflow.com/questions/392932/how-do-i-use-the-conditional-operator. – Michael Karcher Feb 28 '15 at 09:03

1 Answers1

1

This record

:_max_pix_num(0)

in the constructor definition means that data member _max_pix_num of the class is constructed (initialized) using initializer value 0.

When a constructor of a class is called it calls constructors of its data members in the order in which they are declared within the class definition. If you will not explicitly specify what constructor for a data member should be used then the constructor of the class will call the default constructor of the data member. You can explicitly specify what constructor should be used for a data member and what arguments should be supplied to the constructor that to initialize the data member.

Here is an example

struct A
{
    A( int init ) : x( init * init ), y ( init * x )
    {
    }

    int x, y;
}; 

//...

A a( 10 );

std::cout << "a.x = " << a.x << ", a.y = " << a.y " << std::endl;

The output will be

a.x = 100, a.y = 1000

As for this line

_numCamera = ( numCamera > _MAX_IMAGE ) ? _MAX_IMAGE : numCamera;

then there is used so-called conditional (or ternary) operator.

if expression

( numCamera > _MAX_IMAGE )

evaluates to true then _MAX_IMAGE is assigned to _numCamera. Otherwise _numCamera is assigned to itself. That is this statement allows to set _numCamera with a value that is not greater than _MAX_IMAGE.

In fact you can substitute the conditional operator for the following code snippet

if ( numCamera > _MAX_IMAGE )
{
    _numCamera = _MAX_IMAGE;
}
else
{
    _numCamera = _numCamera; 
}

Of course the else statement is redundant for this particular case but it reflects the semantic of the conditional operator.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335