Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

Chapter 16

“Why Do You Build Me Up, Just to Tear Me Down, Baby?”

In This Chapter

Creating and destroying objects

Declaring constructors and destructors

Invoking constructors and destructors

Objects in programs are built and scrapped just like objects in the real world. If the class is to be responsible for its well-being, it must have

some control over this process. As luck would have it (I suppose some pre­ planning was involved as well), C++ provides just the right mechanism. But, first, a discussion of what it means to create an object.

Creating Objects

Some people get a little sloppy in using the terms class and object. What’s the difference? What’s the relationship?

I can create a class Dog that describes the relevant properties of man’s best friend. At my house, we have two dogs. Thus, my class Dog has two instances, Trude (pronounced “Troo-duh”) and Scooter (well, I think there are two instances — I haven’t seen Scooter in a few days).

A class describes a type of thing. An object is one of those things. An object is an instance of a class. There is only one class Dog, no matter how many dogs I have.

Objects are created and destroyed, but classes simply exist. My pets, Trude and Scooter, come and go, but the class Dog (evolution aside) is perpetual.