the first ece250 tutorial - university of waterlooece250/materials/tutorials/... · 2020-01-10 ·...
TRANSCRIPT
The First ECE250 Tutorial C++andClasses
TiuleyAlguindigue(LabInstructor)Winter2020
ECE250C++Tutorial1 1
Outline: The First ECE250 Tutorial
• ReviewObjectOrientedProgramingü Classes–Userdefinedtypesü ClassDesign–UMLnotation
• ReviewC++ü C++arraysü Pointersü Dynamicmemoryallocationü Constructorsü Destructorü Parameterpassingü Overloadingoperators
• DesignandimplementaC++classü Hands-onExample:APolynomialClass
ECE250C++Tutorial1 2
Hands-on Example: Polynomial Definition
• Expressionconsistingofvariablesandcoefficientswithnon-negativeintegerexponents
• Ourexampleconsidersthesinglevariablepolynomial(x)
ECE250C++Tutorial1 3
C++ Background
Question1:intx;//thetypeofxisintPolynomialp1;//p1isan______,aninstanceof______________Question2:p1.setPolynomial(3,10.0,20.0,30.0)p1.evaluate(2.0);p1.print();setPolynomial,evaluateandprintare______________implementedbyclass__________
ECE250C++Tutorial1 4
Example – Class Design
• ClassDiagram–UniversalModelingLanguage(UML)
Polynomial
size:integercoeff[]:double
evaluate():doubleadd(q:Polynomial):Polynomialdiff(q:Polynomial):Polynomialmult(q:Polynomial):Polynomialprint():void
Attributes(membervariablesinC++)
Operationsormethods(memberfunctionsinC++)
Classname
ECE250C++Tutorial1 5
Design Document
• Seesampledocumentprovided(talguind_design_p0.pdf)• Followthisformatforprojects0-4
ECE250C++Tutorial1 6
Polynomial class Example – A first version
Polynomialclass• Membervariables
ü Arraytorepresentpolynomialie.20.0*X+30.0*X**2,representedasP={0.0,20.0,30.0}
ü Sizeofarray(degree+1)ie.size=3inthisexample
• Memberfunctionsü Constructorsü Destructorü addü printü Operators(+,=)
ECE250C++Tutorial1 7
Constructor function
• “Specialfunctionwhichisautomaticallycalledwheneveranewobjectofaclassiscreated,allowingtheclasstoinitializemembervariablesorallocatestorage”
http://www.cplusplus.com/doc/tutorial/classes/• Declaredjustlikearegularmemberfunction,butwithanamethatmatchestheclassnameandwithoutanyreturntype.
Polynomial(const int& size_p, const double coeff_p[]);
ECE250C++Tutorial1 8
Destructor function
• “Destructorsfulfilltheoppositefunctionalityofconstructors:theyareresponsibleforthenecessarycleanupneededbyaclasswhenitslifetimeends.”http://www.cplusplus.com/doc/tutorial/classes2/
• Namedthesameastheclass,precededby~~Polynomial();
ECE250C++Tutorial1 9
Dynamic Memory Allocation
• Thenumberofelementsinthearraythatrepresentsthepolynomialdependsonthedegreeofthepolynomialdouble *coeff; // pointer to array int size ; // degree + 1
• coeff is a pointer to the start of an array that will be dynamically allocated so that it can store “size” elements
ECE250C++Tutorial1 10
Dynamic Memory Allocation
• WhenaPolynomialobjectiscreated–theconstructorfunctioniscalledtoallocateresourcesandinitializetheobject.Inthisfunctionwerequestmemoryforanarray,with“size” elements,eachanumberoftypedouble.
coeff = new double[size];• Inthedestructorfunction,invokedwhenthelifetimeoftheobjectends,wereleasethememorythatwasallocatedforthisobject
delete [] coeff ;
ECE250C++Tutorial1 11
Exercise 1(10 min) • LogintoLEARN,findtheECE250course,anddownloadtoyourlaptopsthefilesfoundunder“Content”,folder“Tutorials”|”Tutorial1”ü Polynomial.h–Polynomialclassinterface(declarations)ü Polynomial.cpp–Polynomialclassimplementationü polynomialtest.cpp-Testprogramwithmain()function
• Examinethesefiles,notedownquestionsyouhave.• Compileandexecutethetestprogram
ü youcanuseanIDE.ü InUNIXlikeenvironmentyouwouldtypethecommands:
g++polynomialtest.cppPolynomial.cpp–opolynomialtest./polynomialtest
ECE250C++Tutorial1 12
What questions do you have?
ECE250C++Tutorial1 13
Question: ConsiderwhatwillchangeintheprovidedimplementationifthePolynomialhadbeenimplementedasa“struct”insteadofa“class”Inthiscoursewewillfavortheuseofclassesvsstructs.Wewillpracticeobject-orientedprogramming,creatingobjectsthatcontainbothdataandmethods.
ECE250C++Tutorial1 14
Using the Polynomial class – a start
// Declaring, initializing, adding two arrays and printing polynomialint main() {
double p1_array[] = {0.0,1.0,3.0};Polynomial p1(3,p1_array); // 3 -terms - 0 + X + 3X**2
Polynomial p1copy(p1); // p1copy is a copy of p1Polynomial p2copy = p2 ; // p2 is copied to p2copy
Polynomial p3;p3 = p1.add(p2); // p3 = p1 + p2p3.print();
}
ECE250C++Tutorial1 15
Access Specifiers in C++
Protecting data members and providing services in your class private–usedfordatamemberspublic –usedformemberfunctions
ECE250C++Tutorial1 16
Polynomial.h – class interface
class Polynomial {
// member variables
private:
double *coeff; // array of coefficients
int size ; // size = degree + 1
ECE250C++Tutorial1 17
Polynomial.h – class interface
// member functions public:
Polynomial (const int& size_p, const double coeff_p[]);
Polynomial();
Polynomial (const Polynomial &polynomial_to_copy);
~Polynomial();
Polynomial add( const Polynomial& right) const ;
void print();
ECE250C++Tutorial1 18
Polynomial class – member functions
Definingfunctionparameters Polynomial add(const Polynomial& right ) const ; Questions: Why the passing by reference - using & ? What will the “const” keyword for the parameter?
ECE250C++Tutorial1 19
Polynomial class - member functions
constmemberfunction Polynomial add( const Polynomial& right) const ;
Question: Why the const keyword for the function declaration?
ECE250C++Tutorial1 20
First Constructor Thefirstconstructor–takesarrayandarraysizeasparameter
Polynomial::Polynomial (const int& ni, const double ci[]){ size = ni; coeff = new double[size]; for(int i = 0; i < size; i++){ coeff[i] = ci[i]; }
}
Precededbyclassname
ECE250C++Tutorial1 21
Arraysarepassedbyreference
Second Constructor
Thesecondconstructor–withoutparameters
Polynomial::Polynomial(){ coeff = 0 ; // There are no elements in the array size = 0;
}
YoumayalternativelyuseaninitializationlistPolynomial::Polynomial():coeff(0),size(0){
}
ECE250C++Tutorial1 22
Third Constructor
Copyconstructor:createsanobjectbasedonanexistingobject.Invokedwhenthiscommandsareexecuted:Polynomial p1copy(p1)
Polynomial p2copy = p2
Questions:
Why is it needed? What will the default copy constructor do for the Polynomial class?
ECE250C++Tutorial1 23
The Destructor
Polynomial::~Polynomial() { delete [] coeff ; // deallocate memory for array
}
ECE250C++Tutorial1 24
The add function
Polynomial Polynomial::add( const Polynomial& right) const {
int temp_size = max(this->size,right.size);
double *temp = new double[temp_size]; // allocate temp array
//Add array in parameter list to array in current object “this”
//Place the resulting polynomial in array temp
// create a new polynomial with the result of addition
Polynomial p(temp_size,temp) ;
delete [] temp; // delete temp array
return p;
}
ECE250C++Tutorial1 25
A “+ “ operator
Polynomial Polynomial::operator+(const Polynomial& right) {
int temp_size = max(this->size,right.size);
double *temp = new double[temp_size]; // allocate temp array
//Add array in parameter list to array in current object “this”
//Place the resulting polynomial in array temp
// create a new polynomial with the result of addition
Polynomial p(temp_size,temp) ;
delete [] temp; // delete temp array
return p;
}
ECE250C++Tutorial1 26
The this keyword
int temp_size = max( this->size ,right.size);
ü this is a pointer to the current object
ü *this is the value of the current object
ECE250C++Tutorial1 27
Using Polynomial “+” operator
int main() {
double p1_array[] = {0.0,1.0,1.0}; Polynomial p1(3,p1_array); // 3 -terms – 0 + X + X**2 double p2_array[] = {1.0,0.0,1.0,2.0}; Polynomial p2(4,p2_array); //4-terms 1 + 0*X + X**2 + 2X**3
Polynomial p3; p3 = p1 + p2;
}
“=“needstobedefined
ECE250C++Tutorial1 28
Polynomial “=” operator // assignment operator that is exception safe - uses the copy-swap idiom Polynomial& Polynomial::operator=(const Polynomial& other) // copy assignment {
// make a copy of the right hand side Polynomial temp(other);
//Now, swap the data members with the temporary
std::swap(size,temp.size); std::swap(coeff,temp.coeff);
return *this ; }
Contentofobject
ECE250C++Tutorial1 29
Exercise 2 – 10 min
• CompletethePolynomialclass
1. Writeevaluate()function–evaluatespolynomialatagivenvalue2. Testallfunctionsandoperators
ü Considerdifferenttestcasesfor“+”operatorü Testthecomparisonoperator(==)
ECE250C++Tutorial1 30
Exercise 3 (lab/home practice)
Completeothermemberfunctionsintheinitialclassdesign:1. diff2. mult3. derivative
ECE250C++Tutorial1 31
Summary
• ReviewObjectOrientedProgramingü Classes–Userdefinedtypesü ClassDesign–UMLnotation
• ReviewC++ü C++arraysü Pointersü Dynamicmemoryallocationü Constructorsü Destructorü Parameterpassingü Overloadingoperators
• DesignandimplementaC++classü Hands-onExample:APolynomialClass
ECE250C++Tutorial1 32
Resources
OnUML• UMLDistilled:ABriefGuidetotheStandardObjectModelingLanguage(3rdEdition)byMartinFowler,Feb242004.
OnC++• DataAbstraction&ProblemSolvingwithC++:WallsandMirrors(7thEdition)bybyFrankM.Carrano,TimothyM.Henry,Mar142016• https://www.tutorialspoint.com/cplusplus/• http://www.cplusplus.com• https://www.learncpp.com/
ECE250C++Tutorial1 33
References
• https://en.wikipedia.org/wiki/Class_diagramClassdiagram• http://www.cplusplus.com/articles/y8hv0pDG/Copyconstructors,assignmentoperators,andexceptionsafeassignment• https://en.wikipedia.org/wiki/Assignment_operator_(C%2B%2B)
ECE250C++Tutorial1 34