11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

222Part III: Introduction to ClassesJustifying constructorsSomething as straightforward as adding arguments to the constructorshouldn’t require much justification, but let me take a shot at it anyway. First,allowing arguments to constructors is convenient. It’s a bit silly to make programmersconstruct a default object and then immediately call an initializationfunction to store data in it. A constructor with arguments is like one-stopshopping — sort of a full-service constructor.Another more important reason to provide arguments to constructors is thatit may not be possible to construct a reasonable default object. Rememberthat a constructor’s job is to construct a legal object (legal as defined by theclass). If some default object is not legal, the constructor isn’t doing its job.For example, a bank account without an account number is probably not legal.(C++ doesn’t care one way or the other, but the bank might get snippy.) Youcould construct a numberless BankAccount object and then require that theapplication use some other member function to initialize the account numberbefore it’s used. This “create now/initialize later” approach breaks the rules,however, because it forces the class to rely on the application for initialization.Using a constructorConceptually, the idea of adding an argument is simple. A constructor is amember function, and member functions can have arguments. Therefore,constructors can have arguments.Remember, though, that you don’t call the constructor like a normal function.Therefore, the only time to pass arguments to the constructor is when theobject is created. For example, the following program creates an object s ofthe class Student by calling the Student(char*) constructor. The object sis destructed when the function main() returns.//// ConstructorWArg - provide a constructor with arguments//#include #include #include using namespace std;const int MAXNAMESIZE = 40;class Student{public:Student(char* pName){strncpy(name, pName, MAXNAMESIZE);name[MAXNAMESIZE - 1] = ‘\0’;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!