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

Size: px
Start display at page:

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

Transcription

1 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 , the instructor described what Kuma is by saying Kuma is a new breed of bear. Kuma has two hands and two legs. Kuma eats, cries, and runs. In terms of object-oriented methodology, the instructor had declared a new class named Kuma with two kind of members: appearance and behaviors. Number of hands and legs describe the appearance of Kuma while eats, cries, and runs describe the behaviors of Kuma. Now that Kuma has been defined, the instructors can simply say Teddy is a Kuma, Cindy is a Kuma, Bunny is a Kuma, Loony is a Kuma, and so on, without the need to define and explain the details of the Kuma over and over again. Teddy, Cindy, Bunny, and Loony are instances Kuma. They are objects of the Kuma class. Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation, and definition Kuma is a new breed of bear. Kuma has two hands and two legs. Kuma eats, cries, and runs. Instantiation Create an object of the class Teddy is a Kuma. Cindy is a Kuma. A class is a structured way that defines what an object is. The process of declaration, creation, and definition of a class and its members is known as abstraction. After the abstraction, programmers can create an object as an instance of the class by using proper C++ code to say the object is an instance of the class. This process is known as instantiation. Abstraction and instantiaion in C++ A class is a data structure specifies both code and data of an object. Programmers create a C++ class and define members of the class for the sake of representing essential features of a data. Once the class is created, they are used in a program as references to describe what these features are. Abstraction is the act of representing an object, while instantiation is the act of creating an object. When defining a class, programmers declare the data it contains and the code that operates on the data. Data is contained in instance variables defined by the class, and code is contained in functions. The code and data that constitute a class are called members of the class. In C++ the class keyword declares a class. The general form of a simple class declaration is: class ClassName private: data and/or methods ; data and/or methods The following is a simple class written as a console application to illustrates the anatomy of a C++ class. Student is the identifier (or name) of the class. A C++ class can be a supportive class, which means it is create to provide a data type. Visual C++ Programming Penn Wu, PhD 149

2 #include <iostream> using namespace std; class Student private: double gpa; string firstname; string lastname; void setgpa(); double getgpa(); void printreport(); ; To compile this code, use: cl.exe filename, where filename must be the correct file name such as lab6.cpp. The compiler; however, will return the following message because this program does not have a main() method. LINK : fatal error LNK1561: entry point must be defined Variables in a class are known as instance variables, and methods in a class can be called instance methods. Variables of a class are typically used to describe a state, property, or appearance of an object, while methods of a class are used to define behavior of an object. The syntax to declare instance variables is: Access-specifiers DataType variablename; The syntax to declare an instance method is: Access-specifiers DataType methodname(); Programmers use Access modifiers, such as private and public, to control accessed to them. The public Access modifier allows them to be accessed by other code outside the class in the program. The private Access modifier limit the access to only members in the class. A later section will discuss about access specfiers in details. The Student class contains two group of members: private and public. The private group consists of a double type of variable named gpa. The public group is made of of two string varaibles, firstname and lastname, and two double type of method, setgpa(), as well as two void type of methods, getgpa() and printreport().in the following example, the instructor adds a main() method and attempts to use it to access two instance variables: firstname and gpa. The access to gpa is denied because it is a private member of the Student class. #include <iostream> #include <string> using namespace std; class Student private: double gpa; Visual C++ Programming Penn Wu, PhD 150

3 string firstname; string lastname; void setgpa(); double getgpa(); void printreport(); ; Student s1; s1.firstname = "Jennifer"; s1.gpa = 3.5; // denied The private group of members can only be accessed by members of the Student class, while the public group of members can be access by external objects, such as s1 inside the main() method which is an external object to the Student class. What is an object? A class in C++ is a new data type by itself. A class definition creates a new data type, and the new data type is represented by the class name. In the above example, the word Student is the name of the class; therefore, it is a newly defined identifier that represents a new data type. The following is the syntax to declare an object of this new data type (which is the act of instantiation ). classname objectid; In the above code, instantiation is done through the following statement. Student s1; Objects are instances of a class, which means a class is essentially a set of plans that specify how to build an object. A class is abstract. It is not until an object of that class has been created that a physical representation of that class exists in memory. A class declaration is only a type description; it does not create an actual object. Thus, the preceding code does not cause any objects of the type Car to come into existence. To actually create a Car object, simply use the following declaration syntax: For example, ClassName ObjectID; Car sedan; // create a Car object called sedan This sedan object is the instance of Car, which inherits all the properties the Car class has. In other words, this sedan object also has two properties, doors and mpg, without you declaring them. Visual C++ automatically applies the properties to sedan, because you clearly said sedan is a Car. An object, after being instantiated, can manage the properties it inherits from the class. To access the properties, use the dot (.) operator, which links the name of an object with the name of a member in the class. The syntax is: objectid.membername; To assign an initial value, use: objectid.membername = value; Visual C++ Programming Penn Wu, PhD 151

4 For example, sedan.doors = 4; // assign value to doors used by sedan sedan.mpg = 35; sedan.mileage(); // use the mileage() method for sedan It is necessary to note that this section describe abstraction and instantiation of a C++ class for console application (native code). However, GUI application written in Visual C++ are managed code. Abtraction and instantiation in managed code Classes in managed code must be declared as reference type. A reference type contains a pointer to another memory location that holds the data. In other words, a reference type of class needs a pointer to indicate the memory address that stores the code of a managed class to the system. Consequently, the way to declare of a managed class is slightly different from the previously discussed. As shown in the following syntax, a reference class type must be prefaced with the ref keyword. The default Access modifier is public. [Access modifier] ref class classname ; // reference class The following is an example of abstraction written in managed code that define what a Car is and provides two instance variables doors and mpg. ref class Car int doors; int mpg; // miles per gallon ; The Car class is a supportive class which can be used in any C++ program that needs its definition, as illustrated by the following example. ref class Car int doors; int mpg; // miles per gallon ; Car^ c1 = gcnew Car(); // instantiation The way to instantiate an object is also different from the previous discussed. First, the class name must followed by a caret sign (^) as a handle in order to declare an instance. To declare an instance c1 of the Car class, use: Car^ c1; Second, you need to use the gcnew keyword to create an instance of the class. In this model, the gcnew keyword creates an instance of a managed type on the garbage collected heap. The Visual C++ Programming Penn Wu, PhD 152

5 result of the evaluation of a gcnew expression is a handle (^) to the type being created. For example, or, simply c1 = gcnew Car(); c1 = gcnew Car; The declaration and instantiation can be done in one statement. For example, or, Car^ c1 = gcnew Car(); Car^ c1 = gcnew Car; A class is a data type; therefore, you can create an array of instance of a given class. The following illustrates how to create an array of the Car class. array<car^>^ c = gcnew array<car^> (3); // an array of Car c[0] = gcnew Car; // first object c[1] = gcnew Car; // second object c[2] = gcnew Car; // third object In the following example, the instructor creates an array of the State class, and then uses a while loop to repeatedly create three instance of the State class. array <State^>^ s = gcnew array<state^> (3); int i=0; while (i<3) s[i] = gcnew State(); // create instance of class i++; The following demonstrates how to use the short-hand way of array creation to create three elements, each is an instance of the Telephone class. array <Telephone^>^ t = gcnew Telephone(), gcnew Telephone(), gcnew Telephone(); In the above code, the Car class does not contain any method (function). The following declares a member method named mileage() to the Car class, ref class Car Visual C++ Programming Penn Wu, PhD 153

6 int doors; int mpg; // miles per gallon void mileage(); // member method ; void Car::mileage() MessageBox::Show(16 * mpg + ""); Some programmers prefer defining the methods of a class inside the class without using the scope resolution operator (::). The above code can be written as: ref class Car int doors; int mpg; // miles per gallon void mileage() MessageBox::Show(16 * mpg + ""); ; The mileage() method performs a simple arithmetic calculation to tell how many mile a full tank (with 16 gallons of gas) a car can run. MessageBox::Show(16 * mpg + ""); When used as a function return type, the void keyword specifies that the function does not return a value to the calling party. void Car::mileage() MessageBox::Show(16 * mpg + ""); The following is a complete code that demonstrate how this Car class can be used. ref class Car int doors; int mpg; // miles per gallon void mileage(); // member method ; void Car::mileage() MessageBox::Show(16 * mpg + ""); Visual C++ Programming Penn Wu, PhD 154

7 Car^ c1 = gcnew Car(); // instantiation c1->mpg = 27; c1->doors = 2; c1->mileage(); It is necessary to note that in native code, the member access operator is a dot (.) sign. In managed code, it is ->. For example, c1->mpg = 27; The following illustrates how to create a value-returning method as a member of a class. It change the type of mileage() method from void to int. ref class Car int doors; int mpg; // miles per gallon int mileage(); // member method that returns int ; int Car::mileage() return 16 * mpg; Car^ c1 = gcnew Car(); c1->doors = 4; c1->mpg = 35; MessageBox::Show(c1->mileage()+""); return 0; One advantage of using managed class is the compliance of the.net Framework. Microsoft encourages the use of managed code to create Windows Forms applications in Visual C++. The GetType() methods provided by the.net Framework, for example, can simplify the finding of the type an object is defined to be. With this support, you can easily determine whether an object is a specific type. The following statement contains this->gettype() to retrieve the name of class (which is Car). The this keyword represent the object that is currently call the mileage() method. void mileage() MessageBox::Show(this->GetType() + " can run " + 16 * mpg + " miles per gallon."); Visual C++ Programming Penn Wu, PhD 155

8 Interestingly, this->gettype()->name can yield the same result as this->gettype() does. Also, the ToString() method can also be used to return a string that represents the current object. For example, void mileage() // member method MessageBox::Show(this->ToString() + " can run " + 16 * mpg + " miles per gallon."); The rest of lecture will focus on the discussion of object-oriented programming written in managed codes. Access modifier In class declarations, members can have Access modifiers. The Access modifiers determines the access to the names that follow it, up to the next access-specifier or the end of the class declaration. C++ class members can be declared as having private, protected, or public access. Specifier Function Example private Can be used only by members of the class. private: int x; protected Can be used by members of the class and other classes that derived the class through inheritance. protected: int y; public Can be used by any part of the program. int z; By the way, using access modifier to control access of class members is part of the concept of encapsulation. In the object-oriented paradigmn, hidding the complexity of how a class actually works from the user is known as encapsulation. Encapsulation is a way to protect variables, functions from outside of class. The following is a sample class, named Apple, that has three members x, y, and z. They are int type and are declared as private, protected, and public accordingly. This code will compile successfully because z is a public member of the Apple class. ref class Apple private: int x; protected: int y; int z; ; Apple^ a1 = gcnew Apple(); a1->z = 3; The following code is illegal because it attempts to access a private member of the Apple class from the main() method which is not part of the Apple class. Visual C++ Programming Penn Wu, PhD 156

9 Apple^ a1 = gcnew Apple(); a1->x = 5; The error message is: error C2248: 'Apple::x' : cannot access private member declared in class 'Apple' 1.cpp(8) : see declaration of 'Apple::x' 1.cpp(7) : see declaration of 'Apple' The following will cause an error message because the main() method attempts to access y, yet y is declared as protected. The function of protected access identifier will clearly magnify in the situation of inheritance. A later lecture will discuss the concept of inheritance. Apple^ a1 = gcnew Apple(); a1->y = 4; The error message is: error C2248: 'Apple::y' : cannot access protected member declared in class 'Apple' 1.cpp(9) : see declaration of 'Apple::y' 1.cpp(7) : see declaration of 'Apple' The following is a completed Student class in managed code that contains private, protected, and public members. ref class Student private: double gpa; protected: DateTime dt; String^ firstname; String^ lastname; void setgpa(int g) gpa = g; double getgpa() return gpa; String^ printreport() dt = DateTime::Now; Visual C++ Programming Penn Wu, PhD 157

10 String^ str = " Report \n"; str += "Name: " + firstname + " " + lastname + "\n"; str += "GPA: " + getgpa() + "\n"; str += "Date: " + dt; return str; ; Student^ s1 = gcnew Student; // create an instance named s1 s1->firstname = "Jennifer"; s1->lastname = "Lopez"; s1->setgpa(3.6); MessageBox::Show(s1->printReport()); The output looks: Advanced class members In addition to methods and properties, object-oriented programmign also allows programmers to create constructors, and fields as members of a class. Fields are simply variables for the class to use without sharing with outsiders (code that are not inside the class). They are typically declared as private members of the class. A telephone set, for example, has data that indicate its make, model, and year. To declare these fields to the Telephone class, simply declare them as private or public variables in the class definition, as in the following code: public ref class Telephone //Fields private: String^ _make; private: String^ _model; private: static String^ _year = "2016"; The above code create three fields for the Telephone class: _make, _model, and _year. The _year fields has a static value (default value). By the way, the instructor adds an underscore as prefix to the names of fields, just to help distinguishing them from the names of properties. Properties are class members that store data for an object, and methods are actions an object can be asked to perform. In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. To add a property to a class, declare a local variable (field) within the class to store the property value. This step is necessary because properties do not allocate any storage on their own. The syntax is: property DataType PropertyName You should declare a property with the public modifier, so it can be used to store data from code blocks outside the class. You need to also declare property with appropriate data type for Visual C++ Programming Penn Wu, PhD 158

11 the property to stores and return data. Unlike a method, a property name cannot be followed by parentheses. The property keyword can be applied to non-static virtual data members in a class. It notifies the compiler to treat these virtual data members as data members by changing their references into function calls. The following example illustrates how to create a String property named Make, public ref class Telephone Telephone() // default constructor //Fields private: String^ _make; private: String^ _model; private: static String^ _year = "2016"; //property property String^ Make String^ get() return _make; void set(string^ value) _make = value; ; The concept of accessors, which is commonly seen in modern object-oriented languages, can apply to managed C++ codes. In most object-oriented language, a property is a code block containing a get accessor and/or a set accessor. The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. The get accessor is executed when the property is read; the set accessor is executed when the property is assigned a new value. The declarations take the following forms: DataType get() return fieldname; void set(datatype value) fieldname = value; The body of the get accessor is similar to that of a method. It must contains the return keyword because it returns the value of the a class field. The execution of the get accessor is equivalent to reading the value of the field. Reading the value of a property is actually reading the value of a field. The set accessor is similar to a method that returns void. It uses an implicit parameter called value, whose type is the type of the property. With the above arrangements, a property can be classified according to the accessors used as follows: A property with a get accessor only is called a read-only property. You cannot assign a value to a read-only property. A property with a set accessor only is called a write-only property. You cannot reference a write-only property except as a target of an assignment. A property with both get and set accessors is a read-write property. For example, // read-write property property String^ Make String^ get() return _make; void set(string^ value) _make = value; Visual C++ Programming Penn Wu, PhD 159

12 // write-only property property String^ Model void set(string^ value) _Model = value; // read-only property property String^ Year String^ get() return _year; Similarly, the Computer class can be re-written to: public ref class Computer // create a managed class Computer() private: String^ dimension; private: String^ weight; property String^ Dimension String^ get() return dimension; void set(string^ value) dimension = value; property String^ Weight String^ get() return weight; void set(string^ value) weight = value; ; The following is a complete and functional code that demonstrates how to create an instance named laptop and how this object uses members of the Computer class. public ref class Computer // create a managed class Computer() private: String^ dimension; private: String^ weight; String^ getdimension() return dimension; void setdimension(string^ _dimension) Visual C++ Programming Penn Wu, PhD 160

13 dimension = _dimension; ; Computer^ laptop = gcnew Computer; laptop->setdimension("24.5 x 15.9"); MessageBox::Show(laptop->getDimension()); Another form of the above code which is more compliant to object-oriented programming looks: public ref class Computer // create a managed class Computer() private: String^ dimension; private: String^ weight; property String^ Dimension String^ get() return dimension; void set(string^ value) dimension = value; property String^ Weight String^ get() return weight; void set(string^ value) weight = value; ; Computer^ laptop = gcnew Computer; laptop->dimension = "24.5 x 15.9"; MessageBox::Show(laptop->Dimension); Constructor and destructor A constructor is a special kind of method of a class that can specify how to actually create instance of a class. There are two kinds of constructors: instance constructors and type constructors. Instance constructors are what the program will run (if available), to learn all the specifications, when an instance of a type is about to create. Instance constructors and the class share the same identifier. In other words, they have the same names. In the following example, the default constructor myclass() has the same identifier (name) as the class which is myclass. The only difference is that a contructor s named must followed by a paird of parentheses. Visual C++ Programming Penn Wu, PhD 161

14 ref class myclass int x; // member field int y; // member field myclass() // default Constructor x = 1; y = 2; myclass(int _x, int _y) // default Constructor x = _x; y = _y; ; myclass^ m1 = gcnew myclass(); // call the default constructor myclass^ m2 = gcnew myclass(3, 4); // call the constructor String^ str = "("+ m1->x + "," + m1->y + ")"; str += "("+ m2->x + "," + m2->y + ")"; MessageBox::Show(str); Instance constructors can take any parameters. Instance constructors that do not take any parameters are often called default constructors. A constructor must always be declared with the public access modifier, and it cannot specify a return type. If the programmers do not explicitly declare any constructors on a class, C++ as well as many programming languages will automatically add a public default constructor. The following is a class that does not declare any default constructor. However, the compiler will add one. ref class myclass int x; // member field int y; // member field ; myclass^ m1 = gcnew myclass(); // call the default contructor m1->x = 3; m1->y = 4; MessageBox::Show(m1->x + "," + m1->y); Visual C++ Programming Penn Wu, PhD 162

15 In object-oriented programming, a destructor is a method which is automatically invoked when the object is destroyed (or deleted). Destructors have the same identifier as the class, except that they are preceded by a '~' operator. ref class myclass private: int x; // member field int y; // member field myclass() //Constructor x = 1; y = 2; ~myclass() //destructor MessageBox::Show("deleted"); ; myclass^ m1 = gcnew myclass(); delete m1; // destory m1 The delete operator is a language-specific operator that can deallocates a block of memory. When delete is used to deallocate memory for a C++ class object, the object s destructor is called before the object's memory is deallocated if the object has a destructor. In a sense, delete is the opposite of gcnew. The syntax is: delete objectid; Abstract class and Virtual functions Microsoft defines an abstract class of Visual C++ as a class that acts as expressions of general concepts from which more specific classes can be derived. That being said, an abstract class is created for other class to inherit it and re-define all its members if necessary. For example, you have a general idea about the term shape, but you currently do not have any firm idea what a shape will be. You can start your program design by declaring and defining an abstract class, as the one shown below: class Shape virtual void drawshape() const = 0; // pure virtual function ; The drawshape() function is declared with the pure specifier (= 0). This declaration pronounces the drawshape() function as a pure virtual function. A virtual function is no different than other virtual function except for a general rule, a pure virtual function in an abstract class has to be implemented by all the derived classes. Otherwise it would result in a Visual C++ Programming Penn Wu, PhD 163

16 compilation error. This approach should be used when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class. The const keyword is option. The above code will work exactly the same as the following declaration. class Shape virtual void drawshape() = 0; // pure virtual function ; A class that contains at least one pure virtual function is considered an abstract class. Classes derived from the abstract class must implement the pure virtual function or they, too, are abstract classes. You cannot create an object of an abstract class type. If you attempt to do so, as shown below, you will get a compiling error. Shape rectangle;.cpp(17) : error C2259: 'Shape' : cannot instantiate abstract class due to following members: 'void Shape::drawShape(void)' : is abstract 36.cpp(11) : see declaration of 'Shape::drawShape' You can use pointers and references to abstract class types. For example, #include <iostream> using namespace std; class Shape virtual void drawshape() const = 0; // pure virtual function ; class Rectangle : public Shape virtual void drawshape() const cout << "Draw the shape!" << endl; ; Rectangle rectangle1; Shape* pt = &rectangle1; // create a pointer pt->drawshape(); return 0; Microsoft s managed code uses the CLI syntax, which makes the declaration of an abstract class slightly different from the console code. First of all, you need to declare both base and derived classes as ref type. and ref class Shape Visual C++ Programming Penn Wu, PhD 164

17 ref class Rectangle : public Shape Second, the override keyword is required when a derived class attempt to override a virtual function of the base. Also the virtual keyword must stay. For example, virtual void drawshape() override Third, managed references use the ^ punctuator. There is no need to use pointer. For example, ref class Shape virtual void drawshape() = 0; // pure virtual function ; ref class Rectangle : public Shape virtual void drawshape() override MessageBox::Show( "Draw the shape!" ); ; Rectangle^ Rectangle1 = gcnew Rectangle; Rectangle1->drawShape(); return 0; User-created header files A well-defined class can be saved a header file; therefore, it can be included in other C++ source files. The following example breaks the above code into two separated files: car.h and 1.cpp. The 1.cpp file is the source code of the C++ program, while car.h is the header file that provides definition of the Car class. By the way, you can rename car.h to car.cpp if you wish. The car.h file ref class Car int doors; int mpg; // miles per gallon int total; int mileage(); ; int Car::mileage() total = 16 * mpg; return total; Visual C++ Programming Penn Wu, PhD 165

18 The 1.cpp file #include "car.h" Car^ c1; c1->doors = 4; c1->mpg = 35; MessageBox::Show(c1.mileage()+""); return 0; The syntax is to include the newly created header file as illustrated below: #include "filename" By making a class in a separated header file, you can use its definitions in as many source codes as you have to. For example, #include "car.h" Car c1; c1.doors = 4; c1.mpg = 35; MessageBox::Show(c1.mileage()+""); return 0; The output looks: 560 The car.h file becomes a header file. You can treat it as a library file with reusable codes. For example, you can create another file named 2.cpp with the followings to create another object SUV. All the members in Car class are, again, shared by the SUV object. #include "car.h" Car c2; c2->doors = 5; c2->mpg = 23; MessageBox::Show(c2.mileage()+""); return 0; Being able to use library code from multiple source files is a very powerful feature. It allows the programmers to extract some of the useful code from a class and save the extracted code in a separated, individual source file. In the following example, the State class has a setstate() method which contains a long but useful (possibly shareable) code. public ref class State... Visual C++ Programming Penn Wu, PhD 166

19 protected: void setstate(string^ st); ; void State::setState(String^ st) if (st=="al") stfullname ="ALABAMA"; else if (st=="ak") stfullname ="ALASKA"; else if (st=="az") stfullname ="ARIZONA"; else if (st=="ar") stfullname ="ARKANSAS";... else if (st=="wy") stfullname ="WYOMING"; else stfullname = "No such stfullname..."; The instructor saved the above highlighted code in an individual source file named states.cpp. public ref class State... protected: void setstate(string^ st); ; #include "states.cpp" This arrangement allows the instructor to use the same source file in a different class named Country. In other word, both State and Country class share the same code of the setstate() method. public ref class Country... protected: void setstate(string^ st); ; #include "states.cpp" Review questions 1. The following code segment does not specific details of the play() method. Which can specify the details of play() outside the Games class? ref class Games void play(); ; A. void play() // details B. void play() : Games // details C. void Games::play() // details D. void Games->play() // details 2. Assume you have created a class named MyClass. The name of the MyClass constructor method is. A. MyClass() B. MyClassConstructor() C. Either of these can be the constructor method name. D. Neither of these can be the constructor method name. Visual C++ Programming Penn Wu, PhD 167

20 3. Given the following code segment, which is the method? A. mytest B. ID C. getid() D. return ref class mytest private: int ID int getid() return ID; 4. Given the following code, which can create an instance named "a1" of Apple in the main() method? ref class Apple... A. Apple a1 = new Apple(); B. Apple a1 = gcnew Apple(); C. Apple^ a1 = new Apple(); D. Apple^ a1 = gcnew Apple(); 5. Given the following code, which can create a default constructor to be added in the body of the Apple class? ref class Apple... A. Apple() B. public^ Apple() C. private: Apple() D. private^ Apple() 6. Which of the following is a valid class declaration? A. ref class A int x; ; B. ref class B C. ref class A D. ref object A int x; ; 7. Which creates a destructor for a class named mytest? A. private: ~mytest() ; B. mytest() ; C. desct mytest() ; D. ~mytest() ; 8. Given the following code, which main() method will compile without error message? ref class Apple private: int x; protected: int y; int z; ; Visual C++ Programming Penn Wu, PhD 168

21 A. Apple^ a1 = gcnew Apple; a1->x = 5; a1->y = 3; B. Apple^ a1 = gcnew Apple; a1->x = 5; a1->z = 2; C. Apple^ a1 = gcnew Apple; a1->y = 3; a1->z = 2; D. Apple^ a1 = gcnew Apple; a1->z = 2; 9. Given the following code, which of the following functions can be called by the main() function without compilation error? ref class Apple private: void findmin() void findmax() protected: void findsum() static void findavg() ; Apple^ a1 = gcnew Apple(); A. a1->findmin(); B. a1->findmax(); C. a1->findsum(); D. a1->findavg(); 10. Given the following code, the output is. A. 18 B. a.my() C. 6 * 3 D. i * 3 ref class myclass int x; void set_values(int i) x = i; int my() return (x * 3); ; myclass^ a = gcnew myclass; a->set_values(6); MessageBox::Show(a->my() + ""); Visual C++ Programming Penn Wu, PhD 169

22 Lab #6 Object-Oriented Programming Learning Activity #1: A simple class 1. Create a directory called C:\cis223 if necessary. 2. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 3. Use Notepad to create a new file named lab6_1.cpp with the following contents: //headers #include "InputBox.cpp" public ref class Car // or simply ref class Car int mpg; // miles per gallon double tanksize; // the class String^ mileage(); // member method ; String^ Car::mileage() return tanksize * mpg + ""; // the main method Car^ c1 = gcnew Car; // first object c1->tanksize = Convert::ToDouble(InputBox::Show("Size of gas tank: ")); c1->mpg = Convert::ToInt32(InputBox::Show("Miles per gallon: ")); Car^ c2 = gcnew Car; // second object c2->tanksize = Convert::ToDouble(InputBox::Show("Size of gas tank: ")); c2->mpg = Convert::ToInt32(InputBox::Show("Miles per gallon: ")); String^ str = "Car\tMPG\tTank Size\tMileage\n"; str += c1->gettype()->name + "1\t" + c1->mpg; str += "\t" + c1->tanksize + "\t" + c1->mileage() + "\n"; str += c2->gettype()->name + "2\t" + c2->mpg; str += "\t" + c2->tanksize + "\t" + c2->mileage() + "\n"; MessageBox::Show(str); return 0; 4. Open the Visual Studio (2010) Command Prompt, type cl /clr lab6_1.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile. The output looks: Visual C++ Programming Penn Wu, PhD 170

23 and and and 5. Download the assignment template, and rename it to lab6.doc if necessary. Capture a screen shot similar to the above figure and paste it to the Word document named lab6.doc (or.docx). Learning Activity #2: 1. Make sure the InputBox.cpp file (you created in Lab #1) is in the C:\cis223 directory. 2. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. and 3. Under the C:\cis223 directory, use Notepad to create a new file named lab6_2.cpp with the following contents: #include "InputBox.cpp" ref class Student private: double gpa; protected: DateTime dt; String^ firstname; String^ lastname; void setgpa(double g) gpa = g; double getgpa() return gpa; String^ printreport() dt = DateTime::Now; String^ str = " Report \n"; str += "Name: " + firstname + " " + lastname + "\n"; str += "GPA: " + getgpa() + "\n"; Visual C++ Programming Penn Wu, PhD 171

24 str += "Date: " + dt; return str; ; Student^ s1 = gcnew Student; // create an instance named s1 s1->firstname = InputBox::Show("First Name: "); s1->lastname = InputBox::Show("Last Name: "); s1->setgpa(convert::todouble(inputbox::show("gpa: "))); MessageBox::Show(s1->printReport()); 4. Compile and test the program. The output looks: and and and 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab6.doc (or.docx). Learning Activity #3: 1. Under the C:\cis223 directory, use Notepad to create a new file named lab6_3.h with the following contents: public ref class Car // or simply ref class Car String^ Make; String^ Model; double msrp; String^ OutOfDoorPrice(double tax); // member method ; String^ Car::OutOfDoorPrice(double tax) return (tax * msrp) + ""; 2. Create another new file named lab6_3.cpp with the following contents: #include "lab6_3.h" String^ str = " REPORT \n"; str += "Make\tModel\tMSRP\tPrice\n"; array <Car^>^ c = gcnew array <Car^> (3); // array of Car c[0] = gcnew Car; Visual C++ Programming Penn Wu, PhD 172

25 c[0]->make = "Toyota"; c[0]->model = "Avalon"; c[0]->msrp = ; c[1] = gcnew Car; c[1]->make = "Nissan"; c[1]->model = "Maximum"; c[1]->msrp = ; c[2] = gcnew Car; c[2]->make = "Subura"; c[2]->model = "Legacy"; c[2]->msrp = ; for (int i=0; i<c->length; i++) // Length = size of c str += c[i]->make + "\t" + c[i]->model; str += "\t$" + c[i]->msrp + "\t$" + c[i]->outofdoorprice(0.085) + "\n"; MessageBox::Show(str); return 0; 3. Compile and test the program. 4. Capture a screen shot similar to the above figure and paste it to the Word document named lab6.doc (or.docx). Learning Activity #4: using get and set accessors 1. Change to the C:\cis223 directory if necessary. 2. Use Notepad to create a new file named lab6_4.cpp with the following contents: public ref class Telephone // or simply ref class Telephone Telephone() // default constructor //Fields private: String^ _make; private: String^ _model; private: static String^ _year = "2026"; // read-write property property String^ Make String^ get() return _make; void set(string^ value) _make = value; Visual C++ Programming Penn Wu, PhD 173

26 // write-only property property String^ Model void set(string^ value) _model = value; // read-only property property String^ Year String^ get() return _year; String^ showmodel() // a function that return _model value return _model; // because Model does not return value ; array <Telephone^>^ t = gcnew Telephone(), gcnew Telephone(), gcnew Telephone(); t[0]->make = "HTC"; t[0]->model = "CS349"; t[1]->make = "Samsung"; t[1]->model = "SG431"; t[2]->make = "Nokia"; t[2]->model = "KT585"; String^ str = "Make\tModel\tYear\n"; for (int i=0; i<t->length; i++) // Length = size of t str += t[i]->make + "\t" + t[i]->showmodel() + "\t" + t[i]->year + "\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 lab6.doc (or.docx). Learning Activity #5: 1. Download the states.zip file, and then extract the states.cpp file to the C:\cis223 directory. 2. Under the C:\cis223 directory, use Notepad to create a new file named lab6_5.cpp with the following contents: Visual C++ Programming Penn Wu, PhD 174

27 #include "InputBox.cpp" public ref class State // or simply ref class State private: // fields String^ st; String^ stfullname; String^ abbr; State() // default constructor st = ""; stfullname = ""; State(String^ s) // constructor st = s->toupper(); setstate(st); abbr = st; String^ getstate() return stfullname; protected: void setstate(string^ st); ; #include "states.cpp" // import library extension String^ str = "Abbr\tState\n"; array <State^>^ s = gcnew array<state^> (3); int i=0; while (i<3) s[i] = gcnew State(InputBox::Show("Enter a state\'s abbreviation: ")); str += s[i]->abbr + "\t" + s[i]->getstate() + "\n"; i++; MessageBox::Show(str); 3. Compile the program. 4. Test the program few times to see how random number can produce different the results. Visual C++ Programming Penn Wu, PhD 175

28 and and and 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab6.doc (or.docx). Submittal 1. Complete all the 5 learning activities and the programming exercise in this lab. 2. Create a.zip file named lab6.zip containing ONLY the following self-executable files. lab6_1.exe lab6_2.exe lab6_3.exe lab6_4.exe lab6_5.exe lab6.doc (or lab6.docx or.pdf) [You may be given zero point if this Word document is missing] 3. Log in to Blackboard, and enter the course site. 4. Upload the zipped file to Question 11 of Assignment 06 as response. 5. Upload ex06.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 06: 1. Launch the Developer Command Prompt. 2. Use Notepad to create a new text file named ex06.cpp. 3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one). //File Name: ex06.cpp //Programmer: [YourFullNameHere] 4. Declares a class named Fruit. The Fruit class has the following public members: one integer variable named qty one double variable named unitprice one double function named total. The total() function must perform the calculation qty * unitprice and return the return to its calling party. 5. In the main() method, create an Fruit object named orange. Assign the following values to the variables of the orange object accordingly: qty is 7 unitprice is In the main() method, create an Fruit object named banana. Assign the following values to the variables of the banana object accordingly: qty is 15 unitprice is In the main() method, call the total() function with reference to the orange object. 8. In the main()method, call the total() function with reference to the banana object. 9. Display the result in a message box. A sample output looks: Visual C++ Programming Penn Wu, PhD 176

29 10. Compile the source code to produce executable code. 11. Download the programming exercise template, and rename it to ex06.doc if necessary. Capture Capture a screen similar to the above one and paste it to the Word document named ex06.doc (or.docx). 12. Compress the source file (ex06.cpp), executable code (ex06.exe), and Word document (ex06.doc) to a.zip file named ex06.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. 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, many programmers argue that C++ is a true object-oriented language. Then, do you think that Visual C++ may not fully comply with object-oriented paradigm? If so, is it a problem? [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 177

#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

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

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

Car. Sedan Truck Pickup SUV

Car. Sedan Truck Pickup SUV 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

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

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

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 Design

Object Oriented Design Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use

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

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

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

Introduction Of Classes ( OOPS )

Introduction Of Classes ( OOPS ) Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

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

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

Lecture 7. Log into Linux New documents posted to course webpage

Lecture 7. Log into Linux New documents posted to course webpage Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next

More information

Polymorphism Part 1 1

Polymorphism Part 1 1 Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid

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

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Data Structures using OOP C++ Lecture 3

Data Structures using OOP C++ Lecture 3 References: th 1. E Balagurusamy, Object Oriented Programming with C++, 4 edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, Data Structures and Program Design in C++, Prentice-Hall 2000.

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

How to engineer a class to separate its interface from its implementation and encourage reuse.

How to engineer a class to separate its interface from its implementation and encourage reuse. 1 3 Introduction to Classes and Objects 2 OBJECTIVES In this chapter you ll learn: What classes, objects, member functions and data members are. How to define a class and use it to create an object. How

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 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? Generalization (pg 29) Sub-typing

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

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

Computer Programming C++ Classes and Objects 6 th Lecture

Computer Programming C++ Classes and Objects 6 th Lecture Computer Programming C++ Classes and Objects 6 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline

More information

Implementing an ADT with a Class

Implementing an ADT with a Class Implementing an ADT with a Class the header file contains the class definition the source code file normally contains the class s method definitions when using Visual C++ 2012, the source code and the

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

More information

A A B U n i v e r s i t y

A A B U n i v e r s i t y A A B U n i v e r s i t y Faculty of Computer Sciences 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 Week 4: Introduction to Classes and Objects Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com

More information

#!"X:\xampp\perl\bin\perl.exe" use CGI qw(:standard); print header, start_html;

#!X:\xampp\perl\bin\perl.exe use CGI qw(:standard); print header, start_html; Lecture #8 Introduction Declaring a subroutine Subroutines In terms of programming, a subroutine is a sequence of program instructions that perform a specific task, packaged as a unit. This unit can then

More information

POINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information

C++ Basic Syntax. Constructors and destructors. Wojciech Frohmberg / OOP Laboratory. Poznan University of Technology

C++ Basic Syntax. Constructors and destructors. Wojciech Frohmberg / OOP Laboratory. Poznan University of Technology Constructors and destructors 1 1 Department of Computer Science Poznan University of Technology 2012.10.07 / OOP Laboratory Outline 1 2 3 4 5 Outline 1 2 3 4 5 Outline 1 2 3 4 5 Outline 1 2 3 4 5 Outline

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

Object Oriented Design

Object Oriented Design Object Oriented Design Lecture 2: Introduction to C++ Class and Object Objects are essentially reusable software components. There are date objects, time objects, audio objects, video objects, automobile

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

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented

More information

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation. Java: Classes Introduction A class defines the abstract characteristics of a thing (object), including its attributes and what it can do. Every Java program is composed of at least one class. From a programming

More information

Chapter 10 Introduction to Classes

Chapter 10 Introduction to Classes C++ for Engineers and Scientists Third Edition Chapter 10 Introduction to Classes CSc 10200! Introduction to Computing Lecture 20-21 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this

More information

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1 Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult

More information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information

Department of Computer science and Engineering Sub. Name: Object oriented programming and data structures Sub. Code: EC6301 Sem/Class: III/II-ECE Staff name: M.Kavipriya Two Mark Questions UNIT-1 1. List

More information

CS24 Week 3 Lecture 1

CS24 Week 3 Lecture 1 CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation

More information

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming Chapter 13: Introduction to Classes 1 13.1 Procedural and Object-Oriented Programming 2 Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a

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

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Learn about class concepts How to create a class from which objects can be instantiated Learn about instance variables and methods How to declare objects How to organize your classes Learn about public

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

More information

Introduction To C#.NET

Introduction To C#.NET Introduction To C#.NET Microsoft.Net was formerly known as Next Generation Windows Services(NGWS).It is a completely new platform for developing the next generation of windows/web applications. However

More information

Appendix M: Introduction to Microsoft Visual C Express Edition

Appendix M: Introduction to Microsoft Visual C Express Edition Appendix M: Introduction to Microsoft Visual C++ 2005 Express Edition This book may be ordered from Addison-Wesley in a value pack that includes Microsoft Visual C++ 2005 Express Edition. Visual C++ 2005

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

More C++ : Vectors, Classes, Inheritance, Templates

More C++ : Vectors, Classes, Inheritance, Templates Vectors More C++ : Vectors,, Inheritance, Templates vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes defined differently can be resized without explicit

More information

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal COMSC-051 Java Programming Part 1 Part-Time Instructor: Joenil Mistal Chapter 4 4 Moving Toward Object- Oriented Programming This chapter provides a provides an overview of basic concepts of the object-oriented

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

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

Lab 12 Object Oriented Programming Dr. John Abraham

Lab 12 Object Oriented Programming Dr. John Abraham Lab 12 Object Oriented Programming Dr. John Abraham We humans are very good recognizing and working with objects, such as a pen, a dog, or a human being. We learned to categorize them in such a way that

More information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

More information

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Grades. Notes (by question) Score Num Students Approx Grade A 90s 7 A 80s 20 B 70s 9 C 60s 9 C

Grades. Notes (by question) Score Num Students Approx Grade A 90s 7 A 80s 20 B 70s 9 C 60s 9 C Grades Score Num Students Approx Grade 100 1 A 90s 7 A 80s 20 B 70s 9 C 60s 9 C Score Num Students Approx Grade 50s 7 C 40s 5 D 30s 3 D 20s 1 F Notes (by question) 1. Use exit to avoid long if-then-else

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

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

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

Lab 4 - Lazy Deletion in BSTs

Lab 4 - Lazy Deletion in BSTs Lab 4 - Lazy Deletion in BSTs Parts A is required. Part B is optional and is worth two points extra credit (but must be submitted in addition to, and along with, Part A). Part C is optional but has no

More information

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13 C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13 This chapter focuses on introducing the notion of classes in the C++ programming language. We describe how to create class and use an object of a

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #13: Java OO cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Homework due next week Problem #2 revisited Constructors, revisited Remember: a

More information

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Learn about class concepts How to create a class from which objects can be instantiated Learn about instance variables and methods How to declare objects How to organize your classes Learn about public

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, Iouliia Skliarova

Object-Oriented Programming, Iouliia Skliarova Object-Oriented Programming, Iouliia Skliarova CBook a = CBook("C++", 2014); CBook b = CBook("Physics", 1960); a.display(); b.display(); void CBook::Display() cout

More information

2. COURSE DESIGNATION: 3. COURSE DESCRIPTIONS:

2. COURSE DESIGNATION: 3. COURSE DESCRIPTIONS: College of San Mateo Official Course Outline 1. COURSE ID: CIS 278 TITLE: (CS1) Programming Methods: C++ C-ID: COMP 122 Units: 4.0 units Hours/Semester: 48.0-54.0 Lecture hours; 48.0-54.0 Lab hours; and

More information

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes CS111: PROGRAMMING LANGUAGE II Lecture 1: Introduction to classes Lecture Contents 2 What is a class? Encapsulation Class basics: Data Methods Objects Defining and using a class In Java 3 Java is an object-oriented

More information

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1 C How to Program, 6/e 1 Structures : Aggregate data types are built using elements of other types struct Time { int hour; int minute; Members of the same structure must have unique names. Two different

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc CST Semester / Year : EVEN / II Subject Name

More information

Scope. Scope is such an important thing that we ll review what we know about scope now:

Scope. Scope is such an important thing that we ll review what we know about scope now: Scope Scope is such an important thing that we ll review what we know about scope now: Local (block) scope: A name declared within a block is accessible only within that block and blocks enclosed by it,

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

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

VB.NET. Exercise 1: Creating Your First Application in Visual Basic.NET

VB.NET. Exercise 1: Creating Your First Application in Visual Basic.NET VB.NET Module 1: Getting Started This module introduces Visual Basic.NET and explains how it fits into the.net platform. It explains how to use the programming tools in Microsoft Visual Studio.NET and

More information

Why C++? C vs. C Design goals of C++ C vs. C++ - 2

Why C++? C vs. C Design goals of C++ C vs. C++ - 2 Why C++? C vs. C++ - 1 Popular and relevant (used in nearly every application domain): end-user applications (Word, Excel, PowerPoint, Photoshop, Acrobat, Quicken, games) operating systems (Windows 9x,

More information

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University User Defined Classes CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Register for Piazza. Deleted post accidentally -- sorry. Direct Project questions to responsible

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

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 14: Object Oriented Programming in C++ (fpokorny@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes

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

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

PART I.   Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++. Unit - III CHAPTER - 9 INTRODUCTION TO C++ Choose the correct answer. PART I 1. Who developed C++? (a) Charles Babbage (b) Bjarne Stroustrup (c) Bill Gates (d) Sundar Pichai 2. What was the original name

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OPERATOR OVERLOADING KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 Dynamic Memory Management

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

Extending Classes (contd.) (Chapter 15) Questions:

Extending Classes (contd.) (Chapter 15) Questions: Extending Classes (contd.) (Chapter 15) Questions: 1 Virtual Functions in C++ Employee /\ / \ ---- Manager 2 Case 1: class Employee { string firstname, lastname; //... Employee( string fnam, string lnam

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.

More information