C ++ constructor question

In C ++ programming for Beginner's absolute book, 2nd edition, there was the following statement:

HeapPoint::HeapPoint(int x, int y): thePoint(new Point(x,y)) { }

Is this equal to:

HeapPoint::HeapPoint(int x, int y) { thePoint = new Point(x,y); }

And, since we do this in the constructor, what are the values ​​assigned to xand y? Should we write the values ​​set in xand yin new Point(x,y)? Or is it right?

UPDATE: I think I came up with the idea of ​​initialization xand y, since in the book it has the following functions:

HeapPoint myHeapPoint(2,4);
+5
source share
6 answers

Generally, you should prefer the first construct, i.e. use an initialization list.

The second construction is preferable if

  • try..catch
  • , , , . , - auto_ptr/unique_ptr, , , . , , , .
+4

, thePoint , . thePoint, , , .

?

  • thePoint - - , , , , , , .
  • thePoint -, , , . , , "", , , .

, , , . . . ( , , ).

, .

+2

, , , (, std:: , int, double .. - ), . , -, . , , , . , -, , . , , - , , : (, GCC) .

+1

.

, , . Point new Point - "" ( , ). , ... , (, ), ( - ) - initialization(Point) vs default initialization followed by assignment.

, , , . , . , , : ( ) . : , , ( ) .

, , , int x int y?

Point.

insted x y (x, y)? ?

( ) , , . , , . :

HeapPoint::HeapPoint(int x, int y): thePoint(new Point(x,y)) { }

, :

const Point* const thePoint;

const , (, Point.x Point.y). , . OP, .

0

. :

HeapPoint::HeapPoint(int x, int y): thePoint(new Point(x,y)) { }

, thePoint, Point.

, thePoint

0

thePoint, . , , , , , , .

:

  • thePoint thePoint(new Point(x,y))

  • first , , , , , , (, , )!! , .

, (++ - , , , C, )! , , , :

class A
{
public:
    B& _b;
    C& _c;

    A(B& b, C& c):_b(b), _c(c) // compiles !
    {

    }

    A(B& b, C& c)
    {
        _b(b); // does not compile !
        _c(c); // does not compile !
    }
}

Keep in mind that here, if we did _c(c), _b(b)in the 1st konstruitore (reverse order), copy constructors of classes Band Cwill be called in the same order they are called in the order in which the members are determined (ie _bbefore _c) and not order you write !!!!

0
source

All Articles