Objectives
- Introduction to classes and objects
- Constructors and destructors
- The scope operator
- Inline functions
Introduction:
The user-defined data types can be defined using the typedef keyword. But creating a data type using the typedef key word can be inadequate in most real life situations. For example, a business application may find the storage and manipulation of dates quite a basic requirement. In such a case the typedef keyword would not help.
C++ offers programmers the capability to define customized user defined data types (like the date) with the help of struct declaration. The declaration could be like:
struct date { int dd; int mm; int yy; };
Here, the biggest drawback in declaring a type like this is the weak ties it would have with its validations and related operations. For example, in the case of the data type int the user cannot enter characters other than numerical ones. The compiler wouldn’t allow him to do so. This is because the validations for this data type have been tied to it at the time of coding itself.
Introduction to Classes and Objects:
A class declaration in C++ is largely similar to a struct declaration. Shown below is the class declaration for the data type date.
class date { int dd; int mm; int yy; };
Notice that the keyword struct has been replaced by the keyword class. However, this definition is not complete. The main idea behind using classes is the binding of data along with its functionality. The modified declaration of the date class, along with a validation: Function would look like this.
class date { int dd; int mm; int yy; void valid (int d, int m) { if(d>31) cout<<”\n date not valid”; if(m>12) cout<<”\n month not valid”; } };
// Classes example #include<iostream.h> class CRectangle { int x,y; public: void set_values (int, int) ; int area() { return(x*y); } }; void CRectangle::set_values(int a, int b) { X=a; Y=b; } int main() { CRectangle rect; rect.set_values(3,4); cout<<”area:”<<rect.area(); return 0; }
//example: one class, two objects #include<iostream.h> class CRectangle { int x,y; public: void set_vlaues(int, int); int area() { return(x*y); } }; void CRectangle::set_values(int a, int b) { X=a; Y=b; } int main() { CRectangle rect, rectb; rect.set_values(3,4); rect.set_values(5,6); cout<<”rect area:”<<rect.area()<<end1; cout<<”rectb area:”<<rectb.area()<<end1; return 0; }
The function valid is now a member of the date data type. Such functions are referred to as member: functions or methods. The data members within the class- dd, mm, yy - are in turn called member data.
Comments/Suggestions are invited. Happy coding......!
Comments Post a Comment