CIS 101: Computer Programming and Problem Solving Lecture11 Usman Roshan Department of Computer...
-
date post
19-Dec-2015 -
Category
Documents
-
view
226 -
download
2
Transcript of CIS 101: Computer Programming and Problem Solving Lecture11 Usman Roshan Department of Computer...
CIS 101: Computer Programming and Problem Solving
Lecture11Usman Roshan
Department of Computer Science
NJIT
Classes
Let’s say we want to define a rectangle object. This is the same defining a new type of variable called rectangle. Previous types we have seen so far are int, char, float, and their pointers.
int length;int width;int area();float diagonal();
This is our rectangle class.it contains the length andwidth, and also functionsto compute the area anddiagonal.
Rectangle
Constructors, destructors, andcopy constructor
• Constructor: get called when a new instance of the object is created.– rectangle myrec; //constructor gets called
• Destructor: gets called when you exit the scope of the variable– void myfunction(){
• rectangle myrec;• myrec.setlength(2); myrec.setwidth(1); myrec.print();
– } //once we exit this function the destructor gets called• Copy constructor: gets called everytime a copy of the object is
created– rectangle myrec2 = myrec;//not called in this case, we’ll have to write
a //separate function for this which (if time) we may see later– void myfunction(rectangle myrec);– void main(){
• rectangle myrec;• myfunction(myrec) //at this point a copy of myrec is created that is local to
//myfunction– }
Overloading constructor
You can have two or more constructors:convert and default
Also called function overloading
Copy constructor
Implicit copy constructor is calledwhich copies width and length ofr1 into width and length of r2.
Strings
mystring
p
size 7
string(int s){ size = s; p = new char[size]; }
string mystring(7);
string( string& from) { size = from.size; p = from.p; }
string mystring2(mystring);
mystring2
p
size 7
Strings
mystring
p
size 7
string(int s){ size = s; p = new char[size]; }
string mystring(7);
string( string& from) { size = from.size;p = new char[size]; for(int i=0;i<size;i++){
p[i]=from.p[i];}
}
string mystring2(mystring);
mystring2
p
size 7