The problem with constructors

Now that we have seen a little about virtual constructors and the Prototype pattern, let's look at exactly what problem we are trying to solve.

To understand the problem of construction, we first need to understand the difference between a class and an object of that class. Classes are what the programmer creates. They are the code template or recipe that the program uses to create objects. In C++, we cannot create classes at runtime. We don't have a way to introduce new code while the program is running.

This is because C++ is a statically typed language. This means that the language tries to prevent operations if they can't be performed on that type at compile time. For example, we can't divide a float by a void* because the C++ compiler checks a compile time if the operation makes sense, and will issue an error if it doesn't.

This static typing in C++ is why we are forced to declare a type for every variable. It is also why we are required to specify the constructor in a case like this:

Base* p = new Derived; 

In this case, the compiler must know the class that we are trying to create. Unfortunately, in C++, classes do not have first class status. That means we can't pass a class as an argument to a function or use a class as a return value. We can't copy a class, save it in a variable, or create one at runtime. Some languages do have these features. Here is an example of what you could do if classes had first class status in C++:

//This isn't real C++ code 
Shape* CreateShape(class theShape)
{
Shape* pShape = new theShape;
return pShape;
}

While this might be useful, we would be trading some type safety for flexibility. The static type checking that the C++ compiler performs has the chance to catch problems before they become bugs at runtime. This is a good thing. We should enjoy the type checking C++ provides. We should also recognize when it has an impact on our code flexibility.

Even though C++ is a statically typed language, we have ways of getting around this problem. One such way was with the factories that we created in the last chapter. We were forced to write the factories ourselves, but we still can choose which class gets created at runtime, while getting the benefits of static typing for all other classes and types. Factories are just one way we can avoid the rigidity of classes not having first class status. The virtual constructor is another way.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.102.50