Why do we have different ways of defining a constructor in C++

Viewed 52

Being very new to c++, I have come across 2 different ways of using a constructor and I am confused on why one of them works, and the other doesen't.

class Journey {
    
protected:
    Coordinate start; 

// this constructor wont work
public:
    Journey(Coordinate startIn)
    {
        start = startIn;
    }
}
  • This constructor does not work as I get the error: constructor for 'Journey' must explicitly initialise the member 'start' which does not have a default constructor
public:
    Journey(Coordinate startIn): start(startIn){
    } 
  • whereas this constructor works perfectly fine
  • Also keep in mind "Coordinate" is just a class I created

I am not sure what the reason is as I thought the 1st way of initialising variables works for all cases, so I just need an explanation why this isn't the case here. I tried looking around for the answer without any success.

1 Answers

There's the concepts of initialization versus assignment. In the first constructor, if Coordinate had a default constructor (which means a constructor that takes no arguments) your start member variable would have been initialized by that constructor. Then, inside your constructor for Journey, you are assigning your start member variable using the argument passed in. That's doing double the work.

In the second Journey constructor, you are initializing the Coordinate member variable via it's constructor and you're done.

Related