Classes Short Review of Topics already covered Member

Classes • Short Review of Topics already covered – – – Member Access Specifiers Accessor methods this Static Class members Class in a namespace Classes with same method in different namespaces • Constructor • Object Initialization • Initialiser List 1

Classes A class is a user-defined type that contains data as well as the set of functions that manipulate the data. We often have a collection of “accessor” accessor methods or functions - sometimes known as “get” get and “set” set methods or functions. Note: Data members of a class cannot be initialized when they are declared private inside the class. These data members should be initialized using specific functions: “set” init in the Point set functions (like init() class). 2

Objects A class is a blueprint for all its objects. class Point{ function members public: void print(); member access specifiers void print(char *s); void init(int u, int v); private: int x, y; data members }; 3

Objects Point my. Point, your. Point; my. Point your. Point Shared behaviour init( int, int) print() print( char*) Specific data x=98, y=57 Specific data x=20, y=100 4

Class Samples 159. 234 Car Date Calendar 5
![#include <iostream> int main(){ using namespace std; Date today; const int Days. In. Month[] #include <iostream> int main(){ using namespace std; Date today; const int Days. In. Month[]](http://slidetodoc.com/presentation_image_h2/b1d1e8cb40b5d08b4c4deb87aedc1547/image-6.jpg)
#include <iostream> int main(){ using namespace std; Date today; const int Days. In. Month[] = { 0, 31, 28, 31, 30, 31 }; enum Months { unused, January, February, March, April, May, June, July, August, September, October, November, December }; today. set. Month( March ); today. set. Day( 12 ); class Date{ Date public: public int get. Day(){ return day; } int get. Month(){ return month; } void set. Day( set. Day int d ){ if( d > 0 && d <= Days. In. Month[month] ){ day = d; } else{ cerr << "Invalid Day value " << d << endl; exit(1); } } void set. Month( set. Month int m ){ if( m >= 1 && m <= 12 ){ month = m; } else{ cerr << "Invalid Month value " << m << endl; exit(1); } } private: private unsigned short int day; // must be 1. . . 31 day unsigned short int month; month // must be 1. . 12 }; cout << "Date is " << today. get. Day() << " of month " << today. get. Month() << endl; today. set. Day( 32 ); return 0; } • Example Output: Date is 12 of month 3 Invalid Day value 32 6
![#include <iostream> using namespace std; namespace Calendar { const int Days. In. Month[] = #include <iostream> using namespace std; namespace Calendar { const int Days. In. Month[] =](http://slidetodoc.com/presentation_image_h2/b1d1e8cb40b5d08b4c4deb87aedc1547/image-7.jpg)
#include <iostream> using namespace std; namespace Calendar { const int Days. In. Month[] = { 0, 31, 28, 31, 30, 31 }; enum Months { unused, January, February, March, April, May, June, July, August, September, October, November, December }; const char *Month. Names[]={"Unused", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; using namespace Calendar; int main(){ Date today; Date tomorrow; today. set. Month( March ); today. set. Day( 12 ); tomorrow. set. Month( March ); tomorrow. set. Day( 13 ); today. print(); tomorrow. print(); class Date{ public: …. // get and set methods code goes here void print(){ print() cout << "Date is " << day << " of " << Month. Names[month] << ", " << year << endl; } private: int day; // instance variable - separate for each instance int month; // instance variable const static int year = 2009; // class variable - its a one-off for all //instances }; } //Calendar cout << "Size of today variable is " << sizeof( today ) << endl; cout << "Size of tomorrow variable is " << sizeof( tomorrow ) << endl; return 0; } • Example Output: Date is 12 of March, March 2009 Date is 13 of March, March 2009 Size of today variable is 8 Size of tomorrow variable is 8 7

Recall A class in C++ is a form of struct whose default access specification is private. Classes have public and private members that provide data hiding. The scope resolution operator : : allows member function of various classes to have the same name as used globals. Static data members are shared by all variables of that class type. Next: Constructors, destructors Textbook p. 149 8

this Nonstatic member functions operate on the class type object they are called with. class X{ public: void f(){//code. . } //more definitions //here. . . }; int main(){ X x, y; x. f(); y. f(); //f operates on x //f operates on y // How does f know which //instance of X it is //operating on? } C++ provides f with a pointer to x called this 9

this Each class variable has a ‘self-referential’ self-referential pointer associated with it. Functions within a class may use the variable this class X { public: X* my. Address(); }; int main() { X x; cout<< x. my. Address(); } X* X: : my. Address(){ return this; this } 10

this class A{ public : void set(int xx, double yy=99. 9){x=xx; y=yy; }//set function int get. X(){return x; } //get function double get. Y(){return y; ) private: int x; double y Do not use this, as it is not necessary! }; class A{ public : void set(int xx, double yy=99. 9){this->x=xx; } this->x. . int get. Y(){return this->y; } this->y. . }; 11

this is a local variable available in the body of any non-static member function; function • this does not need to be declared; (the system does it for you) • this is rarely referred to explicitly in a function definition; • this is used implicitly within the function for member references. (The system effectively uses it for you) • Just occasionally you might want to use “this” yourself. 12

Constructors Variables can be initialised: int j = 5; struct point x = {1, 2}; When we create dynamic structures malloc fills the structure with random data (calloc initialises it all to zeros) Dynamic allocation of objects is very common. C++ includes a mechanism for initialising them, when we use new and delete. 13

Object Initialisation Classes can have a special member function - a constructor - that is called when an object is created. class Point { public: Point(int i, int j); oint x, y; }; Point: : i, int j) oint Point(int oint { x = i; y = j; } The constructor function has the same name as the class name, it has no return type. It is often just inline. 14

Object Initialisation We now create a new point with: Point p(4, 5); or: Point *x; x = new Point(6, 3); This method has a problem though - we can’t ask for an un-initialised point: Point t; produces an error! - In this example, Point now needs two arguments. 15

Object Initialisation We use function overloading to have several versions of the Point constructor function: class Point { public: Point(); Point(int i, int j); private: int x, y; }; Point: : Point(){x = 0; y = 0; } Point: : Point(int i, int j) {x = i; y = j; } 16

Object Initialisation Point t; //now valid!: x, y are 0, 0 A constructor with no arguments is called the default constructor If a class does not contain any constructor the compiler inserts a system default constructor (function). 17

Object Initialisation //this is ok as a default constructor Point: : Point(int i=0, int j=0){ x = i; y = j; } 18
![Object Initialisation Arrays of objects: Point a[100]; can only be initialised using the default Object Initialisation Arrays of objects: Point a[100]; can only be initialised using the default](http://slidetodoc.com/presentation_image_h2/b1d1e8cb40b5d08b4c4deb87aedc1547/image-19.jpg)
Object Initialisation Arrays of objects: Point a[100]; can only be initialised using the default constructor If there is no default constructor for a class, then arrays of that class are not allowed. 19

Initialiser Lists Another way of initialising class variables when using a constructor. Point: : Point() : x(0), y(0){} Point: : Point(int i, int j) : x(i), y(j) {} After the function we write a colon and then a list of variables with their initial values in brackets, separated by commas. Constructor initialisers are in fact the preferred way of setting values. 20

//the most recommended way of writing a default constructor Point : : Point(int i=0, int j=0) : x(i), y(j) { } This notation emphasises that the member data variables x and y are being initialised through the (default) arguments of the default constructor The colon used in this way highlights that here comes an initialiser list. 21

#include <iostream> using namespace std; class XClass{ public: XClass(){ // a default constructor (has no arguments) ID = counter; counter++; } static int get. Counter() { return counter; } int get. ID() { return ID; } static int counter; // keep track of how many instances so far int ID; // objects instantiated will be numbered from zero onwards }; int XClass: : counter = 0; • Note the use of a static variable and function • Note we can have arrays of this class because we have provided a default constructor function // this is needed to initialise counter int main(){ XClass x 1; XClass *xp; cout << "Number of XClasses instantiated so far is: " << XClass: : counter << endl; cout << "ID of x 1 is " << x 1. get. ID() << endl; XClass x 2; XClass xarray[101]; • Example Output: Number of XClasses instantiated so far is: 1 ID of x 1 is 0 Number of XClasses instantiated so far is: 103 ID of xarray[42] is 44 cout << "Number of XClasses instantiated so far is: " << XClass: : counter << endl; xp = &xarray[42]; cout << "ID of xarray[42] is " << xp->get. ID() << endl; return 0; } 22

Summary Non-static data members can use the implicitly declared self-referential pointer this. A constructor creates objects of its class type. This process may involve data members initialization and allocating free store, using operator new. A default constructor is a constructor with no arguments (required for initializing arrays) A system default constructor is one that the system supplies for you; however, it prevents you from declaring arrays of objects of that class. Next: Destructors, Copy Constructors Textbook p. 156 -166, 183 23
- Slides: 23