Wednesday, September 1, 2010

Private constructors

Occasionally, we do not want users outside of a class to use particular constructors. To enforce this behavior, we can make constructors private. Just like regular private functions, private constructors can only be accessed from within the class. Let’s take a look at an example of this:
01class Book
02{
03private:
04    int m_nPages;
05 
06    // This constructor can only be used by Book's members
07    Book() // private default constructor
08    {
09         m_nPages = 0;
10    }
11 
12public:
13    // This constructor can be used by anybody
14    Book(int nPages) // public non-default constructor
15    {
16        m_nPages = nPages;
17    }
18};
19 
20int main()
21{
22    Book cMyBook; // fails because default constructor Book() is private
23    Book cMyOtherBook(242); // okay because Book(int) is public
24 
25    return 0;
26}
One problem with public constructors is that they do not provide any way to control how many of a particular class may be created. If a public constructor exists, it can be used to instantiate as many class objects as the user desires. Often it is useful to restrict users to being able to create only one instance of a particular class. Classes that can only be instantiated once are called singletons. There are many ways to implement singletons, but most of them involve use of a private (or protected) constructor to prevent users from instantiating as many of the class as they want.
Constructor chaining and initialization issues
When you instantiate a new object, the object’s constructor is called implicitly by the C++ compiler. Let’s take a look at two related situations that often cause problems for new programmers:
First, sometimes a class has a constructor which needs to do the same work as another constructor, plus something extra. The process of having one constructor call another constructor is called constructor chaining. Although some languages such as C# support constructor chaining, C++ does not. If you try to chain constructors, it will usually compile, but it will not work right, and you will likely spend a long time trying to figure out why, even with a debugger. However, constructors are allowed to call non-constructor functions in the class. Just be careful that any members the non-constructor function uses have already been initialized.
Although you may be tempted to copy code from the first constructor into the second constructor, having duplicate code makes your class harder to understand and more burdensome to maintain. The best solution to this issue is to create a non-constructor function that does the common initialization, and have both constructors call that function.
For example, the following:
01class Foo
02{
03public:
04    Foo()
05    {
06        // code to do A
07    }
08 
09    Foo(int nValue)
10    {
11        // code to do A
12        // code to do B
13    }
14};
becomes:
01class Foo
02{
03public:
04    Foo()
05    {
06        DoA();
07    }
08 
09    Foo(int nValue)
10    {
11        DoA();
12        // code to do B
13    }
14 
15    void DoA()
16    {
17        // code to do A
18    }
19};
Code duplication is kept to a minimum, and no chained constructor calls are needed.
Second, you may find yourself in the situation where you want to write a member function to re-initialize a class back to default values. Because you probably already have a constructor that does this, you may be tempted to try to call the constructor from your member function. As mentioned, chaining constructor calls are illegal in C++. You could copy the code from the constructor in your function, which would work, but lead to duplicate code. The best solution in this case is to move the code from the constructor to your new function, and have the constructor call your function to do the work of initializing the data:
01class Foo
02{
03public:
04    Foo()
05    {
06        Init();
07    }
08 
09    Foo(int nValue)
10    {
11        Init();
12        // do something with nValue
13    }
14 
15    void Init()
16    {
17        // code to init Foo
18    }
19};
It is fairly common to include an Init() function that initializes member variables to their default values, and then have each constructor call that Init() function before doing it’s parameter-specific tasks. This minimizes code duplication and allows you to explicitly call Init() from wherever you like.
One small caveat: be careful when using Init() functions and dynamically allocated memory. Because Init() functions can be called by anyone at any time, dynamically allocated memory may or may not have already been allocated when Init() is called. Be careful to handle this situation appropriately — it can be slightly confusing, since a non-null pointer could be either dynamically allocated memory or an uninitialized pointer!

No comments:

Post a Comment