Presentation is loading. Please wait.

Presentation is loading. Please wait.

Classes Short Review of Topics already covered Constructor

Similar presentations


Presentation on theme: "Classes Short Review of Topics already covered Constructor"— Presentation transcript:

1 Classes Short Review of Topics already covered Constructor
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

2 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” 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 Point class).

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

4 Objects yourPoint myPoint Point myPoint, yourPoint; 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

5 Class Samples Car Date Calendar

6 Example Output: Date is 12 of month 3 Invalid Day value 32 int main(){
#include <iostream> using namespace std; const int DaysInMonth[] = { 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 }; class Date{ public: int getDay(){ return day; } int getMonth(){ 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; cerr << "Invalid Month value " << m << endl; private: unsigned short int day; // must be unsigned short int month; // 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

7 Example Output: Date is 12 of March, 2009 Date is 13 of March, 2009
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 #include <iostream> using namespace std; namespace Calendar { const int DaysInMonth[] = { 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

8 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

9 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.

10 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(); }

11 Do not use this, as it is not necessary!
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;} .. int getY(){return this->y;} };

12 this this is a local variable available in the body of any non-static member 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.

13 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.

14 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); int x,y; }; Point::Point(int i, int j) { 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.

15 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.

16 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;}

17 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).

18 Object Initialisation
//this is ok as a default constructor Point::Point(int i=0, int j=0){ x = i; y = j; }

19 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.

20 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.

21 //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.

22 Note the use of a static variable and function
#include <iostream> using namespace std; class XClass{ public: XClass(){ // a default constructor (has no arguments) ID = counter; counter++; } static int getCounter() { return counter; } int getID() { 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; // 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; XClass xarray[101]; 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

23 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 , 183


Download ppt "Classes Short Review of Topics already covered Constructor"

Similar presentations


Ads by Google