Download presentation
Presentation is loading. Please wait.
1
CIS 101: Computer Programming and Problem Solving Lecture11 Usman Roshan Department of Computer Science NJIT
2
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 and width, and also functions to compute the area and diagonal. Rectangle
3
Defining classes class { public: ; … private: … };
4
Rectangle class
6
Constructors, destructors, and copy 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 –}–}
7
Constructor Everytime we create a rectangle its length and width are automatically set to 2 and 2.
8
Overloading constructor You can have two or more constructors: convert and default Also called function overloading
9
Copy constructor Implicit copy constructor is called which copies width and length of r1 into width and length of r2.
10
String class
11
Strings mystring p size7 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 size7
12
Strings mystring p size7 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 size7
13
Lab problems 1.Create string class and add functions: 1.Copy string 2.Compare string for equality 3.Concatenate strings 4.Substring 2.Create Vector class 1.Copy vector 2.Vector equality 3.Dot product 4.Euclidean norm (length) of vector
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.