Constructor syntax

Someone could explain me the following declaration for the contructor?

1
2
3
4
5
6
7
8
9
class GameError : public std::exception
{
private:
	int errorCode;
	std::string message;
public:
	// Default constructor
	GameError() throw() :errorCode(gameErrorNS::FATAL_ERROR),
		message( "Undefined Error in game." ) {}
Here the constructor GameError() takes no parameters and has two initializers, for the two member variables errorCode and message, whereas the body of the constructor is just empty. Member variable errorCode is initialized to gameErrorNS::FATAL_ERROR, and message is initialized to "Undefined Error in game.".

Initialization lists are required to specify the parameters to be passed to the constructors of "nested" objects. And to initialize const member variables. They may be used to initialize "primitive" member variables too.

See also:
https://www.cprogramming.com/tutorial/initialization-lists-c++.html
Last edited on
GameError()
This is the default (meaning, 0-arg) constructor.

throw()
This is an outdated syntax for specifying that the function does not throw any exceptions. The old behavior was that if an exception was being thrown and got to this point, std::unexpected would be called, which calls std::terminate.
See: https://en.cppreference.com/w/cpp/language/except_spec

You should use noexcept these days.
https://en.cppreference.com/w/cpp/language/noexcept_spec

1
2
 : errorCode(gameErrorNS::FATAL_ERROR),
   message( "Undefined Error in game." )

This is the member initializer list, which is initializing errorCode to whatever FATAL_ERROR is, and message to "Undefined Error in game."
https://en.cppreference.com/w/cpp/language/constructor
Last edited on
As you browse those those linked pages, you should also notice that

GameError() throw() ; would be a declaration but your

1
2
3
4
5
GameError() throw()
 : errorCode( gameErrorNS::FATAL_ERROR ),
   message( "Undefined Error in game." )
{
}

is a definition as it contains member initializer list and (empty) body for the function.
Last edited on
Topic archived. No new replies allowed.