Embedded Software Colin Walls
Colin Walls has over thirty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles and two books on embedded software, Colin is an embedded software technologist with Mentor … More » Multiple constructors in C++May 18th, 2020 by Colin Walls
C++ is effectively a superset of C. As a result, many developers who are learning the language start from the basis of knowing C. This leads to various aspects of the language being rather surprising. One example results in a common question: What is the idea behind the provision of multiple constructors for a class? … A constructor is a function that is executed automatically when an instance of a class [an object] is created. It has the same name as the class itself. A constructor may optionally take one or more parameters, which are passed values in parentheses after the object name when it is declared. As with any function in C++, a constructor may be overloaded – there may be multiple variants with different combinations of parameters. Imagine a class which handles angles in some way. Perhaps an object needs a starting angle. The value of an angle may be expressed in a number of ways – degrees/minutes/seconds and radians are the obvious options. So, the class might look like this: class angle_stuff { ... public: angle_stuff(float radians); angle_stuff(int degrees, int minutes=0, int seconds=0); ... }; One constructor handles radians and the other degrees etc. Note the use of default parameter values to provide further flexibility. So, possible object declarations are as follows: angle_stuff first(3.141); // radians angle_stuff second(45, 30, 30); // degrees/minutes/seconds angle_stuff third(50, 11); // degrees/minutes angle_stuff fourth(90); // degrees |