Constructors and Integrity Checking

Constructors and Integrity Checking - Constructors and...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Constructors and Integrity Checking Imagine that you want to devise a way to represent calendar dates for use in a C program. You come up with a struct: struct Date { int month; int day; int year; }; and a program using the Date struct can initialize a struct like so: struct Date d; d.month = 9; d.day = 25; d.year = 1956; And you devise various functions, for example one to compute the number of days between two dates: long days_b_dates(struct Date* d1, struct Date* d2); This approach can work pretty well. But what happens if someone says: struct Date d; d.month = 9; d.day = 31; d.year = 1956; and then calls a function like days_b_dates()? The date in this example is invalid, because month 9 (September) has only 30 days. Once an invalid date is introduced, functions that use the date will not work properly. In C, one way to deal with this problem would be to have a function to do integrity checking on each Date pointer passed to a function like days_b_dates(). In C++, a simpler and cleaner approach is to use a constructor to ensure the validity of
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 2

Constructors and Integrity Checking - Constructors and...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online