Loading

C++: Built-in Class Behavior

Built-in Class Behavior

In this C++ console video, we present some of the built-in functionality that is present in classes by default and explain how to disable it. The outgrowth of C++ from C is largely responsible for this legacy functionality, which can cause problems and be difficult to debug for beginning programmers. On the other hand, it is often convenient.

The built-in functionality for classes is listed above. It includes initialization lists and a default constructor, which calls the default constructor on all data members when a class is instantiated. Additionally, we have a copy constructor and an assignment operator which simple copy the memory bitwise—very often, we will need a more sophisticated copy constructor.

In later lessons, we will expand on these points and the issues will be made clearer. For now, we want to make you aware of what you are seeing in classes so that you understand, for instance, that adding a constructor will make prior initialization list instantiations generate errors.

The code above shows a class that holds a single Boolean variable. Our main function demonstrates the use of the built-in default constructor, copy constructor, initialization via a list, and the assignment operator.

In the code segment above, we have added a private copy constructor and an assignment operator. Creating private versions makes these operations unavailable to programmers. We could have also made public versions to change the behavior, as we did with the default constructor. This default constructor assigns the Boolean data member the value of true instead of a strange value it would get from the compiler. Since we have a constructor in this class, the use of initialization lists is now forbidden.

In the code above, we have a constructor that takes a single Boolean argument. In the main function, we begin with an object that is initialized to true and the changed to false via a temporary object and an assignment. The two lines under "Not usable with explicit" are functionally equivalent but disabled by the keyword explicit.