I see some code in a codebase I'm working on that looks like:
ZfooName::ZfooName(int magoo)
: ZfooName()
{
fGoo = magoo;
}
I'm assuming this is a C++11 feature, since it breaks in VS2012, but what does it mean?
The ampersand is part of the type in the declaration and signifies that the type is a reference. Reference is a form of indirection, similar to a pointer.
Every class object is created using the same new keyword, so it must have information about the class to which it must create an object. For this reason, the constructor name should be the same as the class name.
Class: A class in C++ is the building block that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.
A class constructor is a special member function of a class that is executed whenever we create new objects of that class. A constructor will have exact same name as the class and it does not have any return type at all, not even void.
This is a new feature in C++11. It's called a delegating constructor.
The constructor calls the default constructor first (the constructor that is being delegated to). After the default constructor returns, the body of the delegating constructor is executed.
See http://www.stroustrup.com/C++11FAQ.html#delegating-ctor and https://en.cppreference.com/w/cpp/language/initializer_list#Delegating_constructor for additional information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With