Sunday, March 4, 2012

The Orthodox Canonical Class Form

Every "good" programmer has heard it and knows it: the canonical class form, the "must-haves", the four methods every class needs to possess a certain degree of thoroughness in acting out its purpose. In case you have forgotten, I will go ahead and relist them again here:

1. Default Constructor
2. Copy Constructor
3. Assignment Operator
4. Destructor

While this explanation will be stated according to Timothy Budd's Introduction to Object-Oriented Programming book, I believe he does a great job of outlining each of these methods and iterating their purpose to the reader. The default constructor is used to initialize objects and data members when no other value is readily available. There is of course in most cases a default constructor, but relying on the default constructor is typically not a smart choice. The copy instructor is used in the implementation of call-by-value parameters. The assignment operator is rhetorical, and the destructor is invoked when an object is deleted. The copy constructor, to me, seems to always be the least necessary. How often do I actually need to copy an object when I already have access to the original? I typically pass objects as pointers, but I can see how working with others and failing to write a copy constructor could cause somebody to shoot themselves in the foot when passing values by value.
I am sure most readers have these four functions hardwired into their brains, but it is always good to reiterate! I personally fail to always take care of these things, and my goal is that this post will remind me to think through what I am doing and about the issues that can arise when the canonical class form is discarded. I would enjoy hearing some other purposes for the canonical class methods in the comments below!

No comments:

Post a Comment