Car. Sedan Truck Pickup SUV

Size: px
Start display at page:

Download "Car. Sedan Truck Pickup SUV"

Transcription

1 Lecture #7 Introduction Inheritance, Composition, and Polymorphism In terms of object-oriented programming, inheritance is the ability that enables new classes to use the properties and methods of existing classes through the declaration of inheritance. For example, the word car is a general term that can describe many kinds of vehicles including sedan, truck, pickup, SUV, and more. All these vehicles are specialized cars. A car must have an engine, tires, and a driver s seat no matter what kind of car it is. Therefore, if a sedan is a kind of car, then a sedan must have an engine, tires, and a driver s seat. Car Sedan Truck Pickup SUV Fig 1 Inheritance is the act that applies the properties and methods of the Car class to the Sedan class; thus, an instance of Sedan can use members of Car without the need to re-define these Car members in Sedan. A class that is inherited by other classes is called a base class (or parent class). The class that does the inheriting is called a derived class (or child class). In a sense, a derived class is a specialized subset of a base class. Polymorphism is the concept that allows multiple forms of a given method to exist in a class, each of the form is designed for handling a special situation. Polymorphism also allows a child class to override the definition of methods of the parent class. C++ inheritance In C++, programmers create a child class (officially known as derived class ) with the following syntax to declare the inheritance from a parent class (aka base class ), where AccessSpecifier is public, private, or protected. By the way, if no AccessModifier is given, private is the default. class childclassname: AccessModifier parentclassname childclass members; ; The following illustrates how to declare a new class named Cellphone as child (derived) class of an existing class named Telpehone. It is necessary to note that the Telephone class which is the parent (based) class must be declared before the child can be declared. class cellphone: public Telephone After the declaration, the child class can inherit all of the shared members of the base class and create its own menbers. In other words, inheritance is for a child class to gain access to all the public or protected members (such as properties and methods) of the parent class, and use them like its own members. Both public and protected members of a parent class are shareable members to the child class, while private members are not shareable. A later section will discuss how these access modifier work in inheritance. The advantage of inheritance in object-oriented programming is the sharing of codes. In a given program, you only have to define what a car is ONCE by creating a Car class. All the specialized cars, such as sedan, truck, pickup, and SUV, can reference to the Car class Visual C++ Programming Penn Wu, PhD 178

2 and share the codes defined in the Car class. It is just like saying a sedan is a car, a truck is a car, and a pickup is a car without the need to define what a car is over and over again. Class inheritance The following is a class named Car containing two public instance variables: mpg and tanksize. It also has a protected method named mileage() to calculate the mileage, and a private variable named securitycode. The instructor creates this Car class to be inherited by others. ref class Car // base class // open to the entire program int mpg; int tanksize; protected: int mileage() return mpg * tanksize; private: // not open to child class int securitycode; ; The following is an example that create the Sedan class as child to the Car class. The Sedan class also has two public variables of int type: tirenumber and ml. The default constructor, Sedan(), defines all the default values of the Sedan class. All the shareable members of the Car class, mpg, tanksize, and mileage(), are used by the Sedan as its own members. In the words, Sedan inherits all sharable members of Car. Shareable members of Car are also members of the Sedan class. ref class Sedan : public Car // declare Sedan a child of Car int tirenumber; int ml; Sedan() tirenumber = 4; mpg = 34; tanksize = 16; ml = mileage(); ; The declaration on inheritance forces the Car class to share all the public properties and public methods with the Sedan class. Programmers do not need to declare variables mpg and tanksize and the mileage() method again when they create the Sedan class. In other words, the Sedan class inherits all the public members of the Car class. A child class, even as a child, is still an individual class. The way to declare, create, or add members of a child class is exactly the same as that of any C++ class. In the following example, the instructor adds a public method named TurboIt(). Visual C++ Programming Penn Wu, PhD 179

3 ref class Sedan : public Car // declare Sedan a child of Car int tirenumber; int ml; Sedan() tirenumber = 4; mpg = 34; tanksize = 16; ml = mileage(); void TurboIt() mpg = mpg * 1.5; ; Some programmers prefer declaring a class method inside the class body, and then use the scope resolution operator (::) to define details of the member method outside the class body, as illustrated below. The scope resolution operator (::), which, in C++, can be used to define the already declared member functions. ref class Sedan : public Car // declare Sedan a child of Car int tirenumber; int ml; Sedan() tirenumber = 4; mpg = 34; tanksize = 16; ml = mileage(); void TurboIt(); ; void Sedan::TurboIt() mpg = mpg * 1.5; To use members in both base (parent) and derived (child) classes, you can create an instance of Sedan in the main() method, such as s1 in the following code. You can certainly create an instance of Car (s2). Interestingly, you can also declare an object as Car (such as s3 ), but create the object as Sedan. Sedan^ s1 = gcnew Sedan; Car^ s2 = gcnew Car; Car^ s3 = gcnew Sedan; Visual C++ Programming Penn Wu, PhD 180

4 The s1 object is instantiated as Sedan, s2 object is instantiated as a Car, and s3 is declared as Car but is instantiated as Sedan. The difference between s1 and s3 is that s1 can uses all shared members of the Car class through inheritance and every member of the Sedan class, while s3 can use all shared members of Car and the default values defined in the Sedan() constructor. Instance of the Car class can only use any member of the Car class, and cannot access the Sedan() default constructor. Object Car Sedan mpg tanksize mileage() securitycode tirenumber() ml Sedan() s1 yes yes yes no yes yes yes s2 yes yes yes no no no no s3 yes yes yes no no no yes Once Sedan is declared as a derived class (the child class) of the Car class, you can directly use properties and methods of the Car class with the member-of (->) operator. Technically, all the public members in the Car class are treated as members of the Sedan class. For example, to the use mpg property of the Car class from a Sedan object, use: s1->mpg To assign a value to the mpg property, use: s1->mpg = 72; Similarly, to use a method of the Car class, use: s1->mileage(); The following is the complete code. ref class Car // base class // open to the entire program int mpg; int tanksize; protected: int mileage() return mpg * tanksize; private: // not open to child class int securitycode; ; ref class Sedan : public Car // declare Sedan a child of Car int tirenumber; int ml; Sedan() Visual C++ Programming Penn Wu, PhD 181

5 tirenumber = 4; mpg = 34; tanksize = 16; ml = mileage(); void TurboIt() mpg = mpg * 1.5; ; String^ str = "Car\tMPG\tTank Size\tTires\tMileage\n"; Sedan^ s1 = gcnew Sedan; // instance of Sedan s1->turboit(); // member of Sedan only str += "s1\t" + s1->mpg + "\t" + s1->tanksize + "\t"; str += s1->tirenumber + "\t" + s1->ml + "\n"; Car^ s2 = gcnew Car; str += "s2\t" + s2->mpg + "\t" + s2->tanksize + "\n"; Car^ s3 = gcnew Sedan; str += "s3\t" + s3->mpg + "\t" + s3->tanksize + "\t"; //str += s3->tirenumber + "\t" + s3->ml + "\n"; MessageBox::Show(str); The output looks: Access modifiers Choosing a proper Access modifier can make a big difference in inheritance. The private members of a base class are private to the base class only; therefore, the derived class cannot access them. The protected members can be inherited by the derived class; however, the derived class cannot modify values or content of a protected member of the base class. The public members of a base class can be inherited either as public members or as private members by the derived class. In other words, the public members of the base class can become either public or private members of the derived class. The protected Access modifier is similar to private. Its only difference occurs in fact with inheritance. The following table summarizes the different access types according to who can access them in the following way: Access public protected private members of the same class Yes Yes Yes members of derived classes Yes Yes No not members Yes No No Visual C++ Programming Penn Wu, PhD 182

6 In the following example, the instructor declares three instance variables: category, IsRegistered, and origin. They are specified as public, private, and protected respectively. The Car class has a default constructor, Car(), which specifies the default values of IsRegistered and origin. ref class Car // base class String^ category; private: Boolean IsRegistered; protected: String^ origin; Car() IsRegistered = true; origin = "Nakano Japan"; ; The following is a derived class that has only a default constructor, Sedan(), to specify what an instance of the Sedan class should do. It is necessary to note that category is a public member of the Car ; therefore, Sedan can use it and modify its value. Interestingly, origin is a protected member, yet Sedan can still modify its value. This is because Sedan inherits origin from Car which makes origin a member of Sedan. ref class Sedan : public Car Sedan() category = "4 door Sedan"; origin = "Dayton, OH, USA"; MessageBox::Show(category + "\n" + origin); ; In the following example, the instructor attempts to modify the value of orgin inside the main() method. This is an illegal act because the main() method is neither a member of the Sedan class nor a member of the Car class. Sedan s1; s1.origin = "Jechiu, Korea"; The compiler will return the following error message: error C2248: 'Car::origin' : cannot access protected member declared in class 'Car' 1.cpp(13) : see declaration of 'Car::origin' 1.cpp(8) : see declaration of 'Car' Apparently a child class (derived class) can access and modify value or contents of both public and protected members. The following code attempts to access the private member of Car class from the child class. ref class Sedan : public Car Visual C++ Programming Penn Wu, PhD 183

7 Sedan() category = "4 door Sedan"; origin = "Dayton, OH, USA"; IsRegistered = false; MessageBox::Show(category + "\n" + origin); ; The attempt is illegal and the compile will return the following error message: error C2248: 'Car::IsRegistered' : cannot access private member declared in class 'Car' 1.cpp(11) : see declaration of 'Car::IsRegistered' 1.cpp(4) : see declaration of 'Car' The following is the complete code for you to test. ref class Car // base class String^ category; private: Boolean IsRegistered; protected: String^ origin; Car() IsRegistered = true; origin = "Nakano Japan"; ; ref class Sedan : public Car Sedan() category = "4 door Sedan"; origin = "Dayton, OH, USA"; MessageBox::Show(category + "\n" + origin); ; Sedan s1; Default constructor of the parent class is executed by default when inheritance occurs. In the following example, the GetFoot class is the parent class and the GetInch is the child class. By creating an instance of the GetInch class, the default constructor of both classes must execute. The sequence of execution is: parent first, child second. Visual C++ Programming Penn Wu, PhD 184

8 #include "InputBox.cpp" ref class GetFoot protected: int feet; GetFoot() // defaut constructor feet = Convert::ToInt32(InputBox::Show("Enter the feet:")); ; ref class GetInch : GetFoot protected: int inch; int height; GetInch() // default constructor inch = Convert::ToInt32(InputBox::Show("Enter the inch:")); height = feet * 12 + inch; ; String^ str = ""; GetInch^ g1 = gcnew GetInch; // call GetFoot() and GetInch() MessageBox::Show("You are " + g1->height + " inches tall."); return 0; A parent class can share its members with two or more child classes. The following is an example of a supportive class named Socal which is create to provide shared members; therefore, it is a based class. ref class Socal // base class protected: int staff, faculty; void setvalues(int x, int y) staff=x; faculty=y; int total() Visual C++ Programming Penn Wu, PhD 185

9 return (staff + faculty); ; In the Socal (Southern California) area, there are three campuses: Pomona, Long Beach, and Sherman Oaks. Figure 2 explains the relationships among the classes. Socal Pomona Long Beach Sherman Oaks Figure 2 The child classes can inherit and use the shared members of the Socal (parent) class. Noticeably inheritance is a one-way relationship and only the child class can inherit the parent class. The following is a dummy (aka. empty ) which inherits every from the Socal class. ref class ShermanOaks : public Socal ; // an empty class In the following code, the Pomona class inherits the Socal class, yet it modify the public method named total(). ref class Pomona: public Socal // derived class int total() return (staff * faculty * 0.6); ; The Long Beach class can manipulate members of the Socal class in another way (assuming half of the faculties in Long Beach also teach at Pomona, so the formula is different): ref class LongBeach: public Socal // derived class int total() return (staff + faculty / 2); ; The following is the complete code that illustrates the concept. ref class Socal // base class protected: int staff, faculty; void setvalues(int x, int y) Visual C++ Programming Penn Wu, PhD 186

10 staff=x; faculty=y; int total() return (staff + faculty); ; ref class ShermanOaks : public Socal ; // an empty class ref class Pomona: public Socal // derived class int total() return (staff * faculty * 0.6); ; ref class LongBeach: public Socal // derived class int total() return (staff + faculty / 2); ; Pomona^ s1 = gcnew Pomona(); s1->setvalues(15, 7); LongBeach^ s2 = gcnew LongBeach(); s2->setvalues(12, 6); ShermanOaks^ s3 = gcnew ShermanOaks(); s3->setvalues(10, 4); String^ str = "Total employees:\n"; str += s1->total() + "\n" + s2->total() + "\n" + s3->total(); MessageBox::Show(str); return 0; The output looks: Multiple layer inheritance A derived (child) class can be a base (parent) class to its own derived class. For example, a variable x is defined in mybase class. The Square class inherits x from mybase and passes it on Visual C++ Programming Penn Wu, PhD 187

11 to the Cube class. The Square class has a function named calsquare(), which will also be used by the Cube class. MyBase (parent class) Square (child class) Cube (grandchild class) To demonstrate how such a three-layer inheritance works, create the mybase class with a variable x as shown below: ref class mybase double x; ; Create the Square class as a derived class of the mybase class, and then define the calsquare() function as a public member of the Square class. So, the mybase class cannot use this calsquare() function. ref class Square : public mybase int calsquare() // calculate square of x return x * x; ; Create the Cube class as a derived class of the Square class. Technically it is the grandchild of the mybase class. Also, create the calcube() function as the member of the Cube(), so neither Square class nor mybase class can use it. ref class Cube : public Square int calcube() // calculate cube of x return calsquare() * x; ; Finally, in the main() function initiate a Cube object named myno, which will use the x variable (inherited from the mybase class by way of the Square class) and the calsquare() function (inherited from the Square class). ref class mybase double x; ; ref class Square : public mybase int calsquare() // calculate square of x Visual C++ Programming Penn Wu, PhD 188

12 return x * x; ; ref class Cube : public Square int calcube() // calculate cube of x return calsquare() * x; ; Cube^ c1 = gcnew Cube(); c1->x = 3; String^ str = c1->x + "\n"; // inherit x from mybase str += c1->calsquare() + "\n"; // inherit from Square str += c1->calcube() + "\n"; MessageBox::Show(str); return 0; The calcube() function is a member of the Cube class. No inheritance applies to it. The following is another demonstration of how multiple layer inheritance works. The instructor creates three classes. Their relationship is illustrated by the following figure. TicketPrice (parent class) DiscountPrice (child class) InvoicePrice (grandchild class) The functionality of each class is described below: TicketPrice: Ask user to enter the ticket price (or price on a tag), and then set the sale price equal to the unit price. DiscountPrice: Ask user to enter the discount rate and then calculate the sale price. InvoicePrice: Ask user to enter the tax rate, calculate the final price, and rount the value. Based on the above description, the instructor wrote the following code to create the TicketPrice class. ref class TicketPrice // parent double unitprice; double saleprice; TicketPrice() // default constructor unitprice = Convert::ToDouble(InputBox::Show("Unit price: ")); saleprice = unitprice; ; The following is the code for the DiscountPrice. This class inherits both unitprice and saleprice members from the TicketPrice class. It also creates its own member dicsountrate. Visual C++ Programming Penn Wu, PhD 189

13 ref class DiscountPrice : TicketPrice // child double discountrate; DiscountPrice() // default constructor discountrate = Convert::ToDouble(InputBox::Show("Discount rate (%): ")) * 0.01; saleprice = unitprice * (1- discountrate); ; The following is the code for InvoicePrice class. This class inherits both unitprice and saleprice members from the TicketPrice class. It also inherits dicsountrate from the DiscountPrice class. Additionally, it adds two members RoundIt() and taxtrate. ref class InvoicePrice : DiscountPrice // grandchild private: double roundit(double n) return Math::Round(n, 2); protected: double taxrate; double finalprice; InvoicePrice() // default constructor taxrate = Convert::ToDouble(InputBox::Show("Tax rate (%): ")) * 0.01; finalprice = saleprice * (1 + taxrate); finalprice = roundit(finalprice); ; Composition In terms of object-oriented, composition is the creation of a new class which contains instance of other existing classes. The following figure illustrates how a Student class consists of an instance of Name class, an instance of Address class, and an instance of Major class. In other words, every student has a name, an address, and a major. Name n1 Student Address a1 Major m1 The following uses four code snippets to illustrate the concept. ref class Name Ref class Address ref class Major ref class Student Private: Name^ n1; Address^ a1; Major^ m1; Visual C++ Programming Penn Wu, PhD 190

14 The term composition can be further divided into two categories of relationship: composition and aggregation. If an object is exclusively owned by another object, they are in the composition relationship. If an object can be shared by two or more objects, they are in the aggregation relationship. In the above example, each Student must have one and only one Name object; therefore, a Student has a name is a composition relationship. Since two or more students could live in the same house; an address could be shared by two or more student. Student and Address are in an aggregation relationship. The following is a sample code that demonstrates how composition works. ref class Name String^ get() return "object of Name."; ; ref class Address String^ get() return "object of Address."; ; ref class Major String^ get() return "object of Name."; ; ref class Student String^ report; private: Name^ n1 = gcnew Name(); Address^ a1 = gcnew Address(); Major^ m1 = gcnew Major(); Student() report = n1->get() + "\n" + a1->get() + "\n" + m1->get(); ; Student^ s1 = gcnew Student(); MessageBox::Show(s1->report); A sample output looks: Visual C++ Programming Penn Wu, PhD 191

15 In the following example, composition occurs because each Car object must have an Engine object. The instructor, however, purposely creates an instance of Engine inside the default constructor of the Car class. ref class Engine bool IsGasIn; String^ status; Engine() IsGasIn = true; status = "Engine started."; ; ref class Car String^ report; Car() Engine^ e1 = gcnew Engine(); report = e1->status + "\nhas gas: " + e1->isgasin; ; Car^ c1 = gcnew Car(); MessageBox::Show(c1->report); Polymorphism Polymorphism is a biological term that literally means many forms or shapes. The objectoriented paradgin support two major types of polymorphism: method (or function) polymorphism and subclass polymorphism. In terms of programming, method (or function) polymorphism is the ability to allow multiple methods of a given class share the same identifier (name) but behave differently. When building an application for calculating the body mass index (BMI) programmers frequently have to allow a method to behave in serveral ways. BMI is a measure of relative weight based on an individual's mass and height. The following is the formulas used in the U.S. for calculating BMI, where w is the body weight in pounds (lb) and h is the height in inches. BMI = (w /h 2 ) 703 Visual C++ Programming Penn Wu, PhD 192

16 In the following example, the instructor creates two forms of the getbmi() method for the BMI class. Each form takes different types of parameters and return values of different type, yet all the two forms have exactly the same identifier getbmi. This an example of method polymorphism. Some textbook refers this kind of polymorphism as overloading. Overloading happens when you define two or more forms of methods with the same identifier in the same class. ref class BMI double getbmi(double w, double h) // form 1 return (w / (h*h)) * 703; String^ getbmi(int w, int h) //form 2 return ( ((double) w / (h*h)) * 703 ) + ""; ; String^ str = ""; BMI^ b1 = gcnew BMI; str += b1->getbmi(92.7, 1.74) + "\n"; // form 1 str += b1->getbmi(185, 66) + "\n"; // form 2 MessageBox::Show(str); return 0; Polymorphism can happen among functions that do not belong to any class. The following code contains two forms of getf() function. They both use the formula C = (5/9) (F - 32) to convert Fahrenheit to Celsius; however, they take different types of parameter and return values of different types. This example illustrates function polymorphism. double getf(double f) // form 1 return ((double) 5/ (double) 9) * (f - 32); float getf(string^ f) // form 2 return ((double) 5/ (double) 9) * (Convert::ToDouble(f) - 32); Visual C++ Programming Penn Wu, PhD 193

17 String^ str = ""; str += getf(92.7) + "\n"; // form 1 str += getf("92.7") + "\n"; // form 2 MessageBox::Show(str); return 0; Polymorphism can happen between a method of parent class and its child class. Subclass polymorphism is also known as overriding. Overrding happens when you redefine a method inherited from a parent class. There are in fact, two formulas for calculating BMI, as shown in the following table. Metric system BMI = w /h 2 where w is the body weight in kilograms (kg) and h is the height in meters (m). U.S. system BMI = (w /h 2 ) 703 where w is the body weight in pounds (lb) and h is the height in inches. Most countries adapt the metric system. The United States is one of the very few countries that have not yet adapted the metric system; therefore, it is reasonable to treat the U.S. as an exception. In the following code, the instructor creates a paranet class named BMI with a getbmi() method that uses the metric-system formual to return BMI values. The instructor also create a child class named USBMI which inherits public getbmi method from the BMI class. The subclass polymorphism happens when the USBMI class override the getbmi() method. ref class BMI double getbmi(double w, double h) // form 1 return w/(h*h); ; ref class USBMI : BMI double getbmi(double w, double h) // form 2 return (w/(h*h)) * 703; // overriding ; String^ str = ""; BMI^ b1 = gcnew BMI; USBMI^ u1 = gcnew USBMI; str += b1->getbmi(90.3, 1.76) + "\n"; // form 1 str += u1->getbmi(191.6, 66.5) + "\n"; // form 2 MessageBox::Show(str); Visual C++ Programming Penn Wu, PhD 194

18 return 0; The getbmi() method in both BMI and USBMI classes have the same identifier, they take the same types of paremeters, and they return the same type of values. However, they use different formula to calculate the BMI values. Review Question 1. The following is an example of. ref class Blue : public Color A. inheritance. B. encapsulation. C. data hiding. D. abstract data types. 2. Given the following code segment, which statement is correct? ref class Sedan: public Car A. Sedan is a base class B. Car is a derived class C. The Sedan class is a subclass to the Car class. D. The Car class is a subclass to the Sedan class. 3. Given the following code segment,. ref class Apple: public Orange... A. Orange is the derived class B. Orange is the associated class C. Apple is the derived class D. Apple is the base class 4. Given the following code segment,. ref class Apple: public Orange... A. Orange inherits shareable properties and methods from Apple. B. Apple inherits shareable properties and methods from Orange. C. Apple is a derived class, so it cannot add its own class members. D. Apple defines data and features for Orange. 5. Given the following code, which member of the Apple class cannot be accessed by the Orange class. ref class Apple private: double stockprice; protected: double dividend; double shares; ; ref class Orange: public Apple A. stockprice and dividend B. dividend and share C. shares and stockprice Visual C++ Programming Penn Wu, PhD 195

19 D. stockprice 6. Given the following code segment, which statement is correct? ref class Fruit... double size; private: int count; ; A. A derived class can inherit only the "size" variable. B. A derived class can inherit both "size" and "count" variables. C. A derived class can inherit only the "count" variable. D. A derived class cannot inherit "size" and "count" variables. 7. Which function will be execution if you issue a area("3.5") statement? A. int area(int x) // B. double area(double x) // C. String^ area(string^ x) // D. void area() // 8. Given the following code segment, which statement is correct? void print(int i) MessageBox::Show(i); void print(double f) MessageBox::Show(f); A. There are two functions, both are named "print", and they do not overload each other. B. There are two functions called "print", and they can only accept a double data because the one with int is overloaded to accept a double data. C. There is a function called "print", it accepts an int type. There is another function, also called "print", that is meant to overload the previous one to accept a double type of data as input. D. They are two functions with the same name, the overloading keeps the "print" function from accepting either int or double type data as input. 9. Given the following code, which statements in the main() method can yield a message "The sky is blue."? ref class base void func() MessageBox::Show("The sky was blue."); ; ref class child1 : public base void func() MessageBox::Show("The sky is not blue."); ; ref class child2 : public base void func() MessageBox::Show("The sky is blue."); ; A. base^ obj; obj->func(); B. child1^ obj; obj->func(); C. child2^ obj; obj->func(); D. child^ obj; obj->func(); Visual C++ Programming Penn Wu, PhD 196

20 10. Given the following code, which statements in the main() method can yield a message "A Child object!"? class Parent void display() MessageBox::Show("A Parent object!"); ; class Child : public Parent void display() MessageBox::Show("A Child object!"); ; A. Child^ c1; c1->display(); B. Parent^ C1; C1->display(); C. Child : Parent^ c1; c1->display(); D. Parent::Child^ C2; C1->display(); Visual C++ Programming Penn Wu, PhD 197

21 Lab #7 Inheritance and Polymorphism Learning Activity #1: Inheritance 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Under the C:\cis223 directory, use Notepad to create a new file named lab7_1.cpp with the following contents: #include "InputBox.cpp" ref class GetFoot // base class protected: int feet; GetFoot() // defaut constructor feet = Convert::ToInt32(InputBox::Show("Enter the feet:")); ; ref class GetInch : GetFoot // derived class protected: int inch; int height; // member of GetInch GetInch() // default constructor inch = Convert::ToInt32(InputBox::Show("Enter the inch:")); height = feet * 12 + inch; // inherit feet from GetFoot ; String^ str = ""; GetInch^ g1 = gcnew GetInch; MessageBox::Show("You are " + g1->height + " inches tall."); return 0; 3. Open the Visual Studio (2010) Command Prompt, type cl /clr lab6_1.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile. C:\cis223>cl /clr lab6_1.cpp /link /subsystem:windows /ENTRY:main 4. Test the program, the output looks: Visual C++ Programming Penn Wu, PhD 198

22 and and 5. Download the assignment template, and rename it to lab7.doc if necessary. Capture a screen shot similar to the above figure and paste it to the Word document named lab7.doc (or.docx). Learning Activity #2: Inheritance 1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 2. Use Notepad to create a new file named lab7_2.cpp with the following contents: ref class Car // base class // open to the entire program int mpg; int tanksize; protected: int mileage() return mpg * tanksize; private: // not open to child class int securitycode; ; ref class Sedan : public Car // declare Sedan a child of Car int tirenumber; int ml; Sedan() tirenumber = 4; mpg = 34; tanksize = 16; ml = mileage(); void TurboIt() mpg = mpg * 1.5; ; String^ str = "Car\tMPG\tTank Size\tTires\tMileage\n"; Visual C++ Programming Penn Wu, PhD 199

23 Sedan^ s1 = gcnew Sedan; // instance of Sedan s1->turboit(); // member of Sedan only str += "s1\t" + s1->mpg + "\t" + s1->tanksize + "\t"; str += s1->tirenumber + "\t" + s1->ml + "\n"; Car^ s2 = gcnew Car; str += "s2\t" + s2->mpg + "\t" + s2->tanksize + "\n"; Car^ s3 = gcnew Sedan; str += "s3\t" + s3->mpg + "\t" + s3->tanksize + "\t"; //str += s3->tirenumber + "\t" + s3->ml + "\n"; MessageBox::Show(str); 3. Compile and test the program. 4. Capture a screen shot similar to the above figure and paste it to the Word document named lab7.doc (or.docx). Learning Activity #3: Multiple layer inheritance 1. Use Notepad to create a new file named lab7_3.cpp with the following contents: #include "InputBox.cpp" ref class TicketPrice // parent double unitprice; double saleprice; TicketPrice() // default constructor unitprice = Convert::ToDouble(InputBox::Show("Unit price: ")); ; ref class DiscountPrice : TicketPrice // child double discountrate; DiscountPrice() // default constructor discountrate = Convert::ToDouble(InputBox::Show("Discount rate (%): ")) * 0.01; saleprice = unitprice * (1- discountrate); Visual C++ Programming Penn Wu, PhD 200

24 ; ref class SalePrice : DiscountPrice // grandchild private: double roundit(double n) return Math::Round(n, 2); protected: double taxrate; double finalprice; double showtaxrate() return taxrate; SalePrice() // default constructor taxrate = Convert::ToDouble(InputBox::Show("Tax rate (%): ")) * 0.01; finalprice = saleprice * (1 + taxrate); finalprice = roundit(finalprice); ; String^ str = "Unit Price\tDiscount\tTax\tSale Price\n"; SalePrice^ s1 = gcnew SalePrice(); str += "$" + s1->unitprice + "\t$"; str += s1->discountrate + "\t" + s1->showtaxrate() + "\t$" + s1->finalprice; MessageBox::Show(str); return 0; 2. Compile and test the program. and and and 3. Capture a screen shot similar to the above figure and paste it to the Word document named lab7.doc (or.docx). Learning Activity #4: Subclass Polymorphism 1. Use Notepad to create a new file named lab7_4.cpp with the following contents: Visual C++ Programming Penn Wu, PhD 201

25 ref class Socal // base class protected: int staff, faculty; void setvalues(int x, int y) staff=x; faculty=y; int total() // form 1 return (staff + faculty); String^ getcount() return staff + "\t" + faculty + "\t" + total() + "\n"; ; ref class ShermanOaks : public Socal ; // an empty class ref class Pomona: public Socal // derived class int total() // form 2 return (staff * faculty * 0.6); ; ref class LongBeach: public Socal // derived class int total() // form 3 return (staff + faculty / 2); ; Pomona^ s1 = gcnew Pomona(); s1->setvalues(15, 7); LongBeach^ s2 = gcnew LongBeach(); s2->setvalues(12, 6); ShermanOaks^ s3 = gcnew ShermanOaks(); s3->setvalues(10, 4); String^ str = " Employees Count \n"; str += "Staff\tFaculty\tTotal\n"; str += s1->getcount(); str += s2->getcount(); str += s3->getcount(); MessageBox::Show(str); Visual C++ Programming Penn Wu, PhD 202

26 return 0; 2. Compile and test the program. 3. Capture a screen shot similar to the above figure and paste it to the Word document named lab7.doc (or.docx). Learning Activity #5: 1. Use Notepad to create a new file named lab7_5.cpp with the following contents: #include "InputBox.cpp" ref class Sum String^ result; Sum(int n) int sum = 0; for (int i=1; i<=n; i++) sum = sum + i; result = sum + "\n"; ; ref class Factorial String^ result; Factorial(int n) int factorial = 1; for (int i=1; i<=n; i++) factorial = factorial * i; result = factorial + "\n"; ; Visual C++ Programming Penn Wu, PhD 203

27 ref class Average String^ result; Average(int n) double avg; for (int i=1; i<=n; i++) avg = avg + i; result = (avg / n) + "\n"; ; ref class Mymath String^ str; Mymath() String^ option = InputBox::Show("1 - Average, 2 - Factorial, 3 - Sum. [1/2/3]:"); int n = Convert::ToInt32(InputBox::Show("Enter an integer:")); if (option == "1") Average^ a1 = gcnew Average(n); str = a1->result; if (option == "2") Factorial^ f1 = gcnew Factorial(n); str = f1->result; if (option == "3") Sum^ s1 = gcnew Sum(n); str = s1->result; ; Mymath^ m1 = gcnew Mymath(); MessageBox::Show(m1->str); 2. Compile and test the program. and and Visual C++ Programming Penn Wu, PhD 204

28 3. Capture a screen shot similar to the above figure and paste it to the Word document named lab7.doc (or.docx). Submittal 1. Complete all the 5 learning activities and the programming exercise in this lab. 2. Create a.zip file named lab7.zip containing ONLY the following self-executable files. Upload the.zip file to Dropbox. lab7_1.exe lab7_2.exe lab7_3.exe lab7_4.exe lab7_5.exe lab7.doc (or lab7.docx or.pdf) [You may be given zero point if this Word document is missing] 3. Upload the zipped file to Question 11 of Assignment 07 as response. 4. Upload ex07.zip file to Question 12 as response. Note: You will not receive any credit if you submit file(s) to the wrong question. Programming Exercise 07: 1. Launch the Developer Command Prompt. 2. Use Notepad to create a new text file named ex07.cpp. 3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one). //File Name: ex07.cpp //Programmer: [YourFullNameHere] 4. Given the following class mypoly with a function func() which is the first form (form 1), write codes to create three other forms of the func() function. Particularly, one integer form, one double form, one that takes two string parameters. class mypoly String^ func(string^ v1) //form1 return "I took " + v1 + "."; //YourCodeHere ; Form Function Value of n, v1, v2 1 Return a text I took v1. v1: CIS223 where v1 is a value given by the main() method. 2 Return a text I am an 15 integer n. where n is a value given by the main() method. 3 Return a text I am a double value n. where n is a value given by the main() method. 4 Return a text I am a v1 and a v2. where v1 and v2 are string values given by the main() method. v1: student v2: good citizen 5. In the main() method, create a mypoly object named obj. Use this obj object as reference to call each of the four forms of func() function with the value(s) specified in the above table. You must clearly apply polymorphism to the codes to earn the credit, as do the examples provided in the lecture note. [Hint: you may have to use \n to create new lines] 6. The output should looks: Visual C++ Programming Penn Wu, PhD 205

29 7. Compile the source code to produce executable code. 8. Download the programming exercise template, and rename it to ex07.doc if necessary. Capture Capture a screen similar to the above one and paste it to the Word document named ex07.doc (or.docx). 9. Compress the source file (ex07.cpp), executable code (ex07.exe), and Word document (ex07.doc) to a.zip file named ex07.zip. Grading criteria: You will earn credit only when the following requirements are fulfilled. No partial credit is given. You successfully submit both source file and executable file. Your source code must be fully functional and may not contain syntax errors in order to earn credit. Your executable file (program) must be executable to earn credit. You will receive 0 credit if you simply display the messages without applying polymorphism in your code. Threaded Discussion Note: Students are required to participate in the thread discussion on a weekly basis. Student must post at least two messages as responses to the question every week. Each message must be posted on a different date. Grading is based on quality of the message. Question: Class, if you have write a Visual C++ application for three different types of platform, a Windowsbased desktop, a Windows-based tablet, and a Windows-based smartphone, how would you apply the concept of inheritance and polymorphism to the coding design of your application? [There is never a right-or-wrong answer for this question. Please free feel to express your opinion.] Be sure to use proper college level of writing. Do not use texting language. Visual C++ Programming Penn Wu, PhD 206

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms; Lecture #13 Introduction Exception Handling The C++ language provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. Exceptions

More information

Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation, and definition

Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation, and definition Lecture #6 What is a class and what is an object? Object-Oriented Programming Assuming that the instructor found a new breed of bear and decided to name it Kuma. In an email, the instructor described what

More information

Calling predefined. functions (methods) #using <System.dll> #using <System.dll> #using <System.Windows.Forms.dll>

Calling predefined. functions (methods) #using <System.dll> #using <System.dll> #using <System.Windows.Forms.dll> Lecture #5 Introduction Visual C++ Functions A C++ function is a collection of statements that is called and executed as a single unit in order to perform a task. Frequently, programmers organize statements

More information

Table 1: Typed vs. Generic Codes Scenario Typed Generic Analogy Cash Only Multiply Payment Options. Customers must pay cash. No cash, no deal.

Table 1: Typed vs. Generic Codes Scenario Typed Generic Analogy Cash Only Multiply Payment Options. Customers must pay cash. No cash, no deal. Lecture #15 Overview Generics in Visual C++ C++ and all its descendent languages, such as Visual C++, are typed languages. The term typed means that objects of a program must be declared with a data type,

More information

Operating System x86 x64 ARM Windows XP Windows Server 2003 Windows Vista Windows Server 2008 Windows 7 Windows Server 2012 R2 Windows 8 Windows 10

Operating System x86 x64 ARM Windows XP Windows Server 2003 Windows Vista Windows Server 2008 Windows 7 Windows Server 2012 R2 Windows 8 Windows 10 Lecture #1 What is C++? What are Visual C++ and Visual Studio? Introducing Visual C++ C++ is a general-purpose programming language created in 1983 by Bjarne Stroustrup. C++ is an enhanced version of the

More information

#using <System.dll> #using <System.Windows.Forms.dll>

#using <System.dll> #using <System.Windows.Forms.dll> Lecture #8 Introduction.NET Framework Regular Expression A regular expression is a sequence of characters, each has a predefined symbolic meaning, to specify a pattern or a format of data. Social Security

More information

public class Animal // superclass { public void run() { MessageBox.Show("Animals can run!"); } }

public class Animal // superclass { public void run() { MessageBox.Show(Animals can run!); } } Lecture #8 What is inheritance? Inheritance and Polymorphism Inheritance is an important object-oriented concept. It allows you to build a hierarchy of related classes, and to reuse functionality defined

More information

However, it is necessary to note that other non-visual-c++ compilers may use:

However, it is necessary to note that other non-visual-c++ compilers may use: Lecture #2 Anatomy of a C++ console program C++ Programming Basics Prior to the rise of GUI (graphical user interface) operating systems, such as Microsoft Windows, C++ was mainly used to create console

More information

accessmodifier [static] returntype functionname(parameters) { } private string getdatetime() { } public void getdatetime() { }

accessmodifier [static] returntype functionname(parameters) { } private string getdatetime() { } public void getdatetime() { } Lecture #6 User-defined functions User-Defined Functions and Delegates All C# programs must have a method called Main(), which is the starting point for the program. Programmers can also add other methods,

More information

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci) Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci) Sung Hee Park Department of Mathematics and Computer Science Virginia State University September 18, 2012 The Object-Oriented Paradigm

More information

Similarly, example of memory address of array and hash are: ARRAY(0x1a31d44) and HASH(0x80f6c6c) respectively.

Similarly, example of memory address of array and hash are: ARRAY(0x1a31d44) and HASH(0x80f6c6c) respectively. Lecture #9 What is reference? Perl Reference A Perl reference is a scalar value that holds the location of another value which could be scalar, arrays, hashes, or even a subroutine. In other words, a reference

More information

Programming Exercise 14: Inheritance and Polymorphism

Programming Exercise 14: Inheritance and Polymorphism Programming Exercise 14: Inheritance and Polymorphism Purpose: Gain experience in extending a base class and overriding some of its methods. Background readings from textbook: Liang, Sections 11.1-11.5.

More information

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?

More information

using System; using System.Windows.Forms; public class Example { public static void Main() { if (5 > 3) { MessageBox.Show("Correct!

using System; using System.Windows.Forms; public class Example { public static void Main() { if (5 > 3) { MessageBox.Show(Correct! Lecture #4 Introduction The if statement C# Selection Statements A conditional statement (also known as selection statement) is used to decide whether to do something at a special point, or to decide between

More information

CS 115 Exam 1, Fall 2015 Thu. 09/24/2015

CS 115 Exam 1, Fall 2015 Thu. 09/24/2015 CS 115 Exam 1, Fall 2015 Thu. 09/24/2015 Name: Section: Rules and Hints You may use one handwritten 8.5 11 cheat sheet (front and back). This is the only additional resource you may consult during this

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down

More information

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms; Lecture #12 Handling date and time values Handling Date and Time Values In the.net Framework environment, the DateTime value type represents dates and times with values ranging from 12:00:00 midnight,

More information

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 1 Problem Ralph owns the Trinidad Fruit Stand that sells its fruit on the street, and he wants to use a computer

More information

Lesson Plan. Subject: OBJECT ORIENTED PROGRAMMING USING C++ :15 weeks (From January, 2018 to April,2018)

Lesson Plan. Subject: OBJECT ORIENTED PROGRAMMING USING C++ :15 weeks (From January, 2018 to April,2018) Lesson Plan Name of the Faculty Discipline Semester :Mrs. Reena Rani : Computer Engineering : IV Subject: OBJECT ORIENTED PROGRAMMING USING C++ Lesson Plan Duration :15 weeks (From January, 2018 to April,2018)

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Babaria Institute of Technology Computer Science and Engineering Department Practical List of Object Oriented Programming with C

Babaria Institute of Technology Computer Science and Engineering Department Practical List of Object Oriented Programming with C Practical -1 Babaria Institute of Technology LEARN CONCEPTS OF OOP 1. Explain Object Oriented Paradigm with figure. 2. Explain basic Concepts of OOP with example a. Class b. Object c. Data Encapsulation

More information

Software Systems Development Unit AS1: Introduction to Object Oriented Development

Software Systems Development Unit AS1: Introduction to Object Oriented Development New Specification Centre Number 71 Candidate Number ADVANCED SUBSIDIARY (AS) General Certificate of Education 2014 Software Systems Development Unit AS1: Introduction to Object Oriented Development [A1S11]

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Inheritance, and Polymorphism.

Inheritance, and Polymorphism. Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to

More information

Encapsulation in Java

Encapsulation in Java Encapsulation in Java EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Encapsulation (1.1) Consider the following problem: A person has a name, a weight, and a height. A person s

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Suppose you want to drive a car and make it go faster by pressing down on its accelerator pedal. Before you can drive a car, someone has to design it and build it. A car typically begins as engineering

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Cmpt 135 Assignment 2: Solutions and Marking Rubric Feb 22 nd 2016 Due: Mar 4th 11:59pm

Cmpt 135 Assignment 2: Solutions and Marking Rubric Feb 22 nd 2016 Due: Mar 4th 11:59pm Assignment 2 Solutions This document contains solutions to assignment 2. It is also the Marking Rubric for Assignment 2 used by the TA as a guideline. The TA also uses his own judgment and discretion during

More information

Midterm Exam CS 251, Intermediate Programming March 6, 2015

Midterm Exam CS 251, Intermediate Programming March 6, 2015 Midterm Exam CS 251, Intermediate Programming March 6, 2015 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible

More information

Introduction to OOP. Procedural Programming sequence of statements to solve a problem.

Introduction to OOP. Procedural Programming sequence of statements to solve a problem. Introduction to OOP C++ - hybrid language improved and extended standard C (procedural language) by adding constructs and syntax for use as an object oriented language. Object-Oriented and Procedural Programming

More information

CMSC202 Computer Science II for Majors

CMSC202 Computer Science II for Majors CMSC202 Computer Science II for Majors Lecture 14 Polymorphism Dr. Katherine Gibson Last Class We Covered Miscellaneous topics: Friends Destructors Freeing memory in a structure Copy Constructors Assignment

More information

The following is a simple if statement. A later lecture will discuss if structures in details.

The following is a simple if statement. A later lecture will discuss if structures in details. Lecture #2 Introduction What s in a C# source file? C# Programming Basics With the overview presented in the previous lecture, this lecture discusses the language core of C# to help students build a foundation

More information

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

More information

In this lecture, the instructor will guide students through how to implement object-oriented programming in PHP.

In this lecture, the instructor will guide students through how to implement object-oriented programming in PHP. Lecture #13 What is Object- Oriented Programming? Object-Oriented Programming in PHP The concept of object-oriented programming is built on the idea of treating a program as a finished product of many

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

More information

Regis University CC&IS CS310 Data Structures Programming Assignment 2: Arrays and ArrayLists

Regis University CC&IS CS310 Data Structures Programming Assignment 2: Arrays and ArrayLists Regis University CC&IS CS310 Data Structures Programming Assignment 2 Arrays and ArrayLists Problem Scenario The real estate office was very impressed with your work from last week. The IT director now

More information

S T R U C T U R A L M O D E L I N G ( M O D E L I N G A S Y S T E M ' S L O G I C A L S T R U C T U R E U S I N G C L A S S E S A N D C L A S S D I A

S T R U C T U R A L M O D E L I N G ( M O D E L I N G A S Y S T E M ' S L O G I C A L S T R U C T U R E U S I N G C L A S S E S A N D C L A S S D I A S T R U C T U R A L M O D E L I N G ( M O D E L I N G A S Y S T E M ' S L O G I C A L S T R U C T U R E U S I N G C L A S S E S A N D C L A S S D I A G R A M S ) WHAT IS CLASS DIAGRAM? A class diagram

More information

Structured Programming

Structured Programming CS 170 Java Programming 1 Objects and Variables A Little More History, Variables and Assignment, Objects, Classes, and Methods Structured Programming Ideas about how programs should be organized Functionally

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

Data Source. Application. Memory

Data Source. Application. Memory Lecture #14 Introduction Connecting to Database The term OLE DB refers to a set of Component Object Model (COM) interfaces that provide applications with uniform access to data stored in diverse information

More information

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with

More information

CS 1803 Individual Homework 1 Python Practice Due: Wednesday, January 26th, before 6 PM Out of 100 points

CS 1803 Individual Homework 1 Python Practice Due: Wednesday, January 26th, before 6 PM Out of 100 points CS 1803 Individual Homework 1 Python Practice Due: Wednesday, January 26th, before 6 PM Out of 100 points Files to submit: 1. HW1.py This is an INDIVIDUAL assignment! Collaboration at a reasonable level

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Credit where Credit is Due. Lecture 4: Fundamentals of Object Technology. Goals for this Lecture. Real-World Objects

Credit where Credit is Due. Lecture 4: Fundamentals of Object Technology. Goals for this Lecture. Real-World Objects Lecture 4: Fundamentals of Object Technology Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2003 Credit where Credit is Due Some material presented in this lecture

More information

Get Unique study materials from

Get Unique study materials from Downloaded from www.rejinpaul.com VALLIAMMAI ENGNIEERING COLLEGE SRM Nagar, Kattankulathur 603203. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : IV Section : EEE - 1 & 2 Subject Code

More information

index.pdf January 21,

index.pdf January 21, index.pdf January 21, 2013 1 ITI 1121. Introduction to Computing II Circle Let s complete the implementation of the class Circle. Marcel Turcotte School of Electrical Engineering and Computer Science Version

More information

Assignment3 CS206 Intro to Data Structures Fall Part 1 (50 pts) due: October 13, :59pm Part 2 (150 pts) due: October 20, :59pm

Assignment3 CS206 Intro to Data Structures Fall Part 1 (50 pts) due: October 13, :59pm Part 2 (150 pts) due: October 20, :59pm Part 1 (50 pts) due: October 13, 2013 11:59pm Part 2 (150 pts) due: October 20, 2013 11:59pm Important Notes This assignment is to be done on your own. If you need help, see the instructor or TA. Please

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Introduction to Computer Programming

Introduction to Computer Programming Introduction to Computer Programming Lecture 2- Primitive Data and Stepwise Refinement Data Types Type - A category or set of data values. Constrains the operations that can be performed on data Many languages

More information

C++ Data Types and Variables

C++ Data Types and Variables Lecture #3 Introduction C++ Data Types and Variables Data is a collection of facts, such as values, messages, or measurements. It can be numbers, words, measurements, observations or even just descriptions

More information

Topic 7: Algebraic Data Types

Topic 7: Algebraic Data Types Topic 7: Algebraic Data Types 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 5.5, 5.7, 5.8, 5.10, 5.11, 5.12, 5.14 14.4, 14.5, 14.6 14.9, 14.11,

More information

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August Polymorphism, Dynamic Binding and Interface 2 4 pm Thursday 7/31/2008 @JD2211 1 Announcement Next week is off The class will continue on Tuesday, 12 th August 2 Agenda Review Inheritance Abstract Array

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Polymorphism: Inheritance Interfaces

Polymorphism: Inheritance Interfaces Polymorphism: Inheritance Interfaces 256 Recap Finish Deck class methods Questions about assignments? Review Player class for HW9 (starter zip posted) Lessons Learned: Arrays of objects require multiple

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes

More information

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Things to Review Review the Class Slides: Key Things to Take Away Do you understand

More information

Shapes leading to CAD system project

Shapes leading to CAD system project EXERCISES Shapes leading to CAD system project Strings leading to distribution control project Tables leading to infinite precision arithmetic project Conversions leading to instrument control project

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

A Java Execution Simulator

A Java Execution Simulator A Java Execution Simulator Steven Robbins Department of Computer Science University of Texas at San Antonio srobbins@cs.utsa.edu ABSTRACT This paper describes JES, a Java Execution Simulator that allows

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

COMPUTER PROGRAMMING (ECE 431) TUTORIAL 9

COMPUTER PROGRAMMING (ECE 431) TUTORIAL 9 COMPUTER PROGRAMMING (ECE 431) TUTORIAL 9 1. What is object oriented programming (OOP)? How is it differs from the traditional programming? 2. What is a class? How a class is different from a structure?

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

Lecture 18 Tao Wang 1

Lecture 18 Tao Wang 1 Lecture 18 Tao Wang 1 Abstract Data Types in C++ (Classes) A procedural program consists of one or more algorithms that have been written in computerreadable language Input and display of program output

More information

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++ No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)

More information

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More information

CGS 2405 Advanced Programming with C++ Course Justification

CGS 2405 Advanced Programming with C++ Course Justification Course Justification This course is the second C++ computer programming course in the Computer Science Associate in Arts degree program. This course is required for an Associate in Arts Computer Science

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017 OOP components For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Data Abstraction Information Hiding, ADTs Encapsulation Type Extensibility Operator Overloading

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University OOP Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation Inheritance

More information

The following table distinguishes these access modifiers.

The following table distinguishes these access modifiers. Lecture #7 Introduction User-Defined Functions and Delegates In programming, a function is defined as named code block that can perform a specific task. Some programming languages make a distinction between

More information

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill Chapter 12 OOP: Creating Object-Oriented Programs McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter Objectives - 1 Use object-oriented terminology correctly Create a two-tier

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

CS 162, Lecture 25: Exam II Review. 30 May 2018

CS 162, Lecture 25: Exam II Review. 30 May 2018 CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you

More information

Object Oriented Programming 2012

Object Oriented Programming 2012 1. Write a program to display the following output using single cout statement. Maths = 90 Physics =77 Chemestry =69 2. Write a program to read two numbers from the keyboard and display the larger value

More information

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

[Page 177 (continued)] a. if ( age >= 65 ); cout << Age is greater than or equal to 65 << endl; else cout << Age is less than 65 << endl; Page 1 of 10 [Page 177 (continued)] Exercises 4.11 Identify and correct the error(s) in each of the following: a. if ( age >= 65 ); cout

More information

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

COMP 105 Homework: Type Systems

COMP 105 Homework: Type Systems Due Tuesday, March 29, at 11:59 PM (updated) The purpose of this assignment is to help you learn about type systems. Setup Make a clone of the book code: git clone linux.cs.tufts.edu:/comp/105/build-prove-compare

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Final Examination Semester 3 / Year 2012

Final Examination Semester 3 / Year 2012 Final Examination Semester 3 / Year 2012 COURSE : ADVANCED JAVA PROGRAMMING COURSE CODE : PROG 2114 TIME : 2 1/2 HOURS DEPARTMENT : COMPUTER SCIENCE LECTURER : LIM PEI GEOK Student s ID : Batch No. : Notes

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Object-Oriented Programming. Objects. Objects. Objects

Object-Oriented Programming. Objects. Objects. Objects References: Beginning Java by Jacquie Barker; Designing Object-Oriented Software by Rebecca Wirfs- Brock;Object-oriented Analysis & Design by Grady Booch; Sara Stoecklin Object Oriented Programming defined

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING Wednesady 23 rd March 2016 Afternoon Answer any FOUR questions out of SIX. All

More information

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question) CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers

More information

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department 0901212 Python Programming 1 st Semester 2014/2015 Course Catalog This course introduces

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object-Oriented Programming (OOP) Fundamental Principles of OOP Object-Oriented Programming (OOP) O b j e c t O r i e n t e d P r o g r a m m i n g 1 Object-oriented programming is the successor of procedural programming. The problem with procedural programming is

More information

Procedures. This is a common situation -- there is some functionality that computers should have that the do not the solution is to write a procedure

Procedures. This is a common situation -- there is some functionality that computers should have that the do not the solution is to write a procedure Procedures Procedures are familiar in everyday life -- they are a standard process for achieving some objective. Procedures in computers are similar: They are a standard process of computing some result.

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

Object Oriented Software Development CIS Today: Object Oriented Analysis

Object Oriented Software Development CIS Today: Object Oriented Analysis Object Oriented Software Development CIS 50-3 Marc Conrad D104 (Park Square Building) Marc.Conrad@luton.ac.uk Today: Object Oriented Analysis The most single important ability in object oriented analysis

More information

PART A : MULTIPLE CHOICE Circle the letter of the best answer (1 mark each)

PART A : MULTIPLE CHOICE Circle the letter of the best answer (1 mark each) PART A : MULTIPLE CHOICE Circle the letter of the best answer (1 mark each) 1. An example of a narrowing conversion is a) double to long b) long to integer c) float to long d) integer to long 2. The key

More information

Inheritance (Deitel chapter 9)

Inheritance (Deitel chapter 9) Inheritance (Deitel chapter 9) 1 2 Plan Introduction Superclasses and Subclasses protected Members Constructors and Finalizers in Subclasses Software Engineering with Inheritance 3 Introduction Inheritance

More information

CS304 Object Oriented Programming

CS304 Object Oriented Programming 1 CS304 Object Oriented Programming 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes?

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 1 2 Data and expressions reading: 2.1 3 The computer s view Internally, computers store everything as 1 s and 0

More information