Classes Short Review of Topics already covered Constructor

Slides:



Advertisements
Similar presentations
Introduction to Programming Lecture 34. In Today’s Lecture Arrays of objects Arrays of objects Interaction of Arrays with Free Store Interaction of Arrays.
Advertisements

Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
C++ Review (3) Structs, Classes, Data Abstraction.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
2011 Calendar Important Dates/Events/Homework. SunSatFriThursWedTuesMon January
Programming II Array of objects. this Using the this Pointer this Objects use the this pointer implicitly or explicitly. – this is – this is used implicitly.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.
11 Introduction to Object Oriented Programming (Continued) Cats.
1 Classes classes and objects - from object-oriented programming point of view class declaration class class_name{ data members … methods (member functions)
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
1 Classes struct Public and Private Parts of a struct Class Scope of a Class Overloading Member Functions Class in a Class Static Members of Classes this.
CMSC 202 Lesson 8 Classes II. Warmup Declare a class (.h part) named “Cup” It has a data member that says how full it is One method called “Drink” that.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
COMP 53 – Week Two Operator Overloading.
Eine By: Avinash Reddy 09/29/2016.
Procedural and Object-Oriented Programming
Submission Example May 14, 2018
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
CSC241: Object Oriented Programming
Review: Two Programming Paradigms
CS410 – Software Engineering Lecture #11: C++ Basics IV
Introduction to Classes
Object-Oriented Programming
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Chapter 5 Classes.
This pointer, Dynamic memory allocation, Constructors and Destructor
group work #hifiTeam
Static Data Member and Functions
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Introduction to Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Classes and Data Abstraction
Chapter 5 Function Basics
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Java Classes and Objects
CMSC 202 Classes and Objects.
Introduction of Programming
UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
McDonald’s calendar 2007.
9-10 Classes: A Deeper Look.
Classes and Objects Static Methods
CMSC202 Computer Science II for Majors Lecture 07 – Classes and Objects (Continued) Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
CS 144 Advanced C++ Programming February 21 Class Meeting
CMSC 202 Lesson 8 Classes II.
CS31 Discussion 1D Winter18: week 6
CS31 Discussion 1H Fall18: week 9
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
McDonald’s calendar 2007.
Pointers, Dynamic Data, and Reference Types
More C++ Classes Systems Programming.
9-10 Classes: A Deeper Look.
Object Oriented Programming (OOP) Lecture No. 12
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
(4 – 2) Introduction to Classes in C++
2015 January February March April May June July August September
Presentation transcript:

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

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

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

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

Class Samples 159.234 Car Date Calendar

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 1...31 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

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

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

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

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

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.

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

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

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

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 no default 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(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.

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

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

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