240 likes | 284 Views
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. Classes. Classes.
E N D
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 Classes
Classes A classis a user-defined type that contains data as well as the set of functionsthat manipulate the data. We often have a collection of “accessor” methods or functions - sometimes known as “get” and “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” functions (like init() in the Pointclass).
Objects A class is a blueprint for all its objects. class Point{ public: private: intx,y;}; function members void print(); void print(char *s); void init(int u,int v); member access specifiers data members
Objects Point myPoint, yourPoint; yourPoint myPoint Shared behaviour init( int,int) print() print( char*) Shared behaviour init( int,int) print() print( char*) Specific data x=98, y=57 Specific data x=20, y=100
159.234 Class Samples Car Date Calendar
#include <iostream> using namespace std; const intDaysInMonth[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; enumMonths { unused, January, February, March, April, May, June, July, August, September, October, November, December }; class Date{ public: intgetDay(){ return day; } intgetMonth(){ return month; } void setDay( int d ){ if( d > 0 && d <= DaysInMonth[month] ){ day = d; } else{ cerr << "Invalid Day value " << d << endl; exit(1); } } void setMonth( int m ){ if( m >= 1 && m <= 12 ){ month = m; } else{ cerr << "Invalid Month value " << m << endl; exit(1); } } private: unsigned short intday; // must be 1...31 unsigned short intmonth; // must be 1..12 }; int main(){ Date today; today.setMonth( March ); today.setDay( 12 ); cout << "Date is " << today.getDay() << " of month " << today.getMonth() << endl; today.setDay( 32 ); return 0; } Example Output: Date is 12 of month 3 Invalid Day value 32
#include <iostream> using namespace std; namespace Calendar{ const intDaysInMonth[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; enum Months { unused, January, February, March, April, May, June, July, August, September, October, November, December }; const char *MonthNames[]={"Unused", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; class Date{ public: …. // get and set methods code goes here void print(){ cout << "Date is " << day << " of " << MonthNames[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 using namespace Calendar; int main(){ Date today; Date tomorrow; today.setMonth( March ); today.setDay( 12 ); tomorrow.setMonth( March ); tomorrow.setDay( 13 ); today.print(); tomorrow.print(); 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, 2009 Date is 13 of March, 2009 Size of today variable is 8 Size of tomorrow variable is 8
Recall A class in C++ is a form of struct whose default access specification is private. Classes have publicand privatemembers 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
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(); //f operates on x y.f(); //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.
this Each class variable has a ‘self-referential’ pointer associated with it. Functions within a class may use the variable this. class X { public: X*myAddress(); }; X* X::myAddress(){ return this; } int main() { X x; cout<< x.myAddress(); }
this class A{ public : void set(int xx, double yy=99.9){x=xx;y=yy;}//set function int getX(){return x;} //get function double getY(){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;} .. intgetY(){return this->y;} .. };
this • thisis a local variable available in the body of any non-static member function; • thisdoes not need to be declared; (the system does it for you) • thisis rarely referred to explicitly in a function definition; • thisis used implicitly within the function for member references. (The system effectively uses it for you) • Just occasionally you might want to use “this” yourself.
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.
Object Initialisation Classes can have a special member function - a constructor- that is called when an object is created. class Point { public: Point(inti, int j); intx,y; }; Point::Point(inti, int j) { x = i; y = j;} The constructor function has thesame nameas the class name, it has noreturn type. It is often just inline.
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.
Object Initialisation We use function overloadingto have several versions of the Pointconstructor function: class Point { public: Point(); Point(inti, int j); private: intx,y; }; Point::Point(){x = 0; y = 0;} Point::Point(inti, int j) {x = i; y = j;}
Object Initialisation Point t;//now valid!:x,yare 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).
Object Initialisation //this is ok as a default constructor Point::Point(int i=0, int j=0){ x = i; y = j; }
Object Initialisation Arrays of objects: Point a[100]; can only be initialised using the default constructor. If there is nodefault constructor for a class, then arrays of that class are not allowed.
Initialiser Lists Another way of initialising class variables when using a constructor. Point::Point() : x(0), y(0){} Point::Point(inti,int j) : x(i), y(j) {} After the function we write a colonand then a list of variables with their initial values in brackets, separated by commas. Constructor initialisersare in fact the preferred way of setting values.
//the most recommended way of writing a default constructor Point:: Point(inti=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 colonused in this way highlights that here comes an initialiser list.
#include <iostream> using namespace std; class XClass{ public: XClass(){ // a default constructor (has no arguments) ID = counter; counter++; } static intgetCounter() { return counter; } intgetID() { return ID; } static int counter; // keep track of how many instances so far int ID; // objects instantiated will be numbered from zero onwards }; intXClass::counter = 0; // this is needed to initialise counter int main(){ XClass x1; XClass *xp; cout << "Number of XClasses instantiated so far is: " << XClass::counter << endl; cout << "ID of x1 is " << x1.getID() << endl; XClass x2; XClassxarray[101]; cout << "Number of XClasses instantiated so far is: " << XClass::counter << endl; xp = &xarray[42]; cout << "ID of xarray[42] is " << xp->getID() << endl; return 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 Example Output: Number of XClasses instantiated so far is: 1 ID of x1 is 0 Number of XClasses instantiated so far is: 103 ID of xarray[42] is 44
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