OOPortal
OOPortal

Constructor Functions
«Prev
Next»
## C++ Constructor Function Conclusion

### Constructors

Wouldn’t it be nice to be able to initialize a rational object with a numerator and denominator, and have them
properly reduced automatically? You can do that by writing a special member function that looks and acts a little like
assign, except the name is the same as the name of the type (rational), and the function has no return type or return
value.

Listing 4-11 shows how to write this special member function.

**Listing 4-11**

### CPlus Constructor - Quiz

Lesson 11

In this module you learned how to use constructor member functions to create objects from classes.

In particular, you learned:

In particular, you learned:

- How constructors and destructors provide management of class-defined objects
- How to use a constructor for initialization
- About the use of default constructors
- How to use constructor initializers
- How constructors can perform automatic conversions

Objects generally need to initialize variables or assign dynamic memory during their process of creation to become operative and to avoid returning unexpected values during their execution. A class can include a special function called a *constructor*, which is automatically called whenever a new object of this class is created. This constructor function must have the same name as the class, and cannot have any return type.

Listing 4-11 shows how to write this special member function.

#include <cassert> #include <cstdlib> #include <iostream> /* Compute GCD of two integers, using Euclid’s algorithm. */ int gcd(int n, int m) { n = std::abs(n); while (m != 0) { int tmp(n % m); n = m; m = tmp; } return n; }

/// Represent rational number. struct rational { /// Construct rational object, given numerator and denominator. /// Always reduce to normal form. /// @param num numerator /// @param den denominator /// @pre denominator > 0 rational(int num, int den) : numerator{num}, denominator{den} { reduce(); }

/// Assign numerator and denominator, then reduce to normal form. /// @param num numerator /// @param den denominator /// @pre denominator > 0 void assign(int num, int den) { numerator = num; denominator = den; reduce(); }

/// Reduce the numerator and denominator by their GCD. void reduce() { assert(denominator != 0); int div{gcd(numerator, denominator)}; numerator = numerator / div; denominator = denominator / div; } int numerator; /// < numerator gets the sign of the rational value int denominator; ///< denominator is always positive };

int main() { rational pi{1420, 452}; std::cout << "pi is about " << pi.numerator << "/" << pi.denominator << '\n'; }

Click the Quiz link below to take a multiple-choice quiz covering the topics presented in this module.

**C++ Constructor - Quiz**