34
Visual C++ Programming Penn Wu, PhD 222 Lecture #8 Object-Oriented Programming What is a class and what is an object? Assuming that the instructor found a new breed of “bear” and decided to name it “Kuma”. In an email, 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.” The following is the sample content of the email which is a pseudocode and is not written in any programming language. class Kuma { String specifies = "new breed of bear"; int numberOfHands = 2; int numberOfLegs = 2; void eat() { } void cry() { } void run() { } } In terms of object-oriented methodology, the instructor had declared a new class named “Kuma” with two kinds 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. The following is the pseudocode that demonstrates how to create “instances” of “Kuma”. Kuma Teddy = new Kuma; Kuma Cindy = new Kuma; Kuma Bunny = new Kuma; Kuma Loony = new Kuma; “Teddy”, “Cindy”, “Bunny”, and “Loony” are instances of the “Kuma” class. They are said to be “objectsof the “Kuma” class. A “class”, in terms of object-oriented paradigm, 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”. The following table explains what “abstraction” and “instantiation” are. 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”.

Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 222

Lecture #8 Object-Oriented Programming

What is a class

and what is an

object?

Assuming that the instructor found a new breed of “bear” and decided to name it “Kuma”. In

an email, 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.” The following is the sample

content of the email which is a pseudocode and is not written in any programming language.

class Kuma

{

String specifies = "new breed of bear";

int numberOfHands = 2;

int numberOfLegs = 2;

void eat() { }

void cry() { }

void run() { }

}

In terms of object-oriented methodology, the instructor had declared a new class named

“Kuma” with two kinds 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. The following is the

pseudocode that demonstrates how to create “instances” of “Kuma”.

Kuma Teddy = new Kuma;

Kuma Cindy = new Kuma;

Kuma Bunny = new Kuma;

Kuma Loony = new Kuma;

“Teddy”, “Cindy”, “Bunny”, and “Loony” are instances of the “Kuma” class. They are said to

be “objects” of the “Kuma” class.

A “class”, in terms of object-oriented paradigm, 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”. The following table explains what “abstraction” and “instantiation” are.

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”.

Page 2: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 223

Object-oriented programming (OOP) is a conceptual programming model (known as

“paradigm”) that organizes the definition of program objects (such as data and methods) to

enhance the modularity and reusability of coding. One simply analogy is to consider object-

oriented programming as a reference model that provides feasible framework to write

“modularized” codes that can be “plugged-in” to other programs to support features. A

wireless “mouse”, for example, is a “modularized” device that can be connected to any laptop

to provide the “pointing device” feature. “Can work with any laptop” is the “reusability” of the

wireless mouse as a “module”.

The rest of lecture will focus on the discussion of object-oriented programming written in

managed codes.

Abstraction and

instantiation in

C++

A “class” is a data structure that specifies both code and data of an “object”. Programmers

create a Visual 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.

In Visual C++, the class keyword declares a class. The following is a generic form of class

declaration in Visual C++, where accressModifiers are options like “public”, “private”, and

“protected”; and type could be “ref” for managed reference type while identifier is a unique

name given to the class. The class body must be enclosed by a pair of curly braces and must be

ended with a semicolon (;).

accessModifier type class identifier

{

private: data and/or methods

public: data and/or methods

};

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. A reference class type must be prefaced with the “ref” keyword. By the way,

the default access modifier of a “reference” class is “public”.

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

{

public:

int doors;

int mpg; // miles per gallon

};

The following is sample class of the “ref” type whose identifier is “Discount”. It has five

members: one variable named “dt” with “private” access modifier, two variables of float type

named “rate” and “price” with “public” modifier, and a method of float type named

“getDiscount()”. The “getDiscount()” method will perform an arithmetic calculation and return

the rounded result to its calling party. There is a special type of class method, known as

“constructor”. A later section will discuss about what “class constructors” are. In the following

example, the constructor is “Discount()” which has the same identifier as the “Discount” class.

By the way, “dt” is declared as DateTime type.

public ref class Discount

Page 3: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 224

{

private:

DateTime dt = DateTime::Now;

public:

float rate;

float price;

public:

Discoun() { rate=0.0; } //default constructor

float getDiscount()

{

return Math::Round(price * (1 - rate/100), 2);

}

};

Variables of the “Discount” class are known as “instance variable”, meaning that they will be

implemented by the “instance” of the class. Variables of a class are typically used to describe a

“state”, “property”, or “appearance” of an object. When defining a class, programmers declare

the data the class will contain 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. The following is the syntax for

declaring instance variables, access-specifiers are options like “private”, “public”, and

“protected”.

Access-specifiers: DataType variableName;

The following is an example.

public: float rate;

While variables in a class are known as “instance variables”, and methods in a class can be

called “instance methods”. Methods of a class are used to define “behavior” of an object. The

following is the syntax for declaring an instance method.

Access-specifiers DataType methodName() { }

The following is an example.

public: float getDiscount() { }

Programmers use “access modifiers”, such as “private” and “public”, to specify the access

control of a class member; therefore “access modifiers” are also known as “access specifiers”.

The discussion of this lecture will focus on “public” and “private” access modifiers. A later

lecture will discuss the “protected” modifier in detail. The following table illustrates the

usages.

Modifier Scope Ownership public “public” class members can be access by any program

objects regardless the objects are inside or outside the

class.

Not specified

private “private” class members can only be accessed by members

of the same class.

The class

Page 4: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 225

The public modifier simply indicates that the entity can be accessed by code in any place of

the same program. If an entity is declared with a private modifier, it will be accessible only to

the code that is contained within the class that defines the entity.

In the following example, 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 one String variables named “firstName”. Inside the “main()” function, the codes

attempt to access these two “instance variables”, “firstName” and “gpa”. The access to “gpa”

is denied because it is a “private” member of the “Student” class, while the access to

“firstName” is granted because its modifier is “public”.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

ref class Student

{

private:

double gpa;

public:

String^ firstName;

Student() { } //default constructor

};

int main()

{

Student^ s1;

s1 = gcnew Student();

s1->firstName = "Jennifer"; // allowed

s1->gpa = 3.5; // denied

}

The following figure illustrates how the “public” modifier keeps external code items from

accessing “private members”.

In Visual C++, declaring a “ref” class without specifying the “access modifier” will be

assumed to be “publicly declared”; therefore, the “public” modifier of the “Student” class can

be omitted.

With “public” modifier Without “public” modifier

public ref class Student { }

ref class Student { }

The next section will discuss the concept of “instantiation” in detail.

private: double gpa

Public: string^ fristName

int main() {

.........

s1->firstName = "Jennifer";

s1->gpa = 3.5;

}

NO

Page 5: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 226

What is an

object?

The term “object” is used in object-oriented programming to refer to an instance of a class. A

class in Visual C++ can be considered a new data type created by programmers. The definition

of the class describes the new data type, so an “object” can be treated as a variable of the new

data type. The following is the syntax to declare an instance of a class.

className objectID;

The following illustrates how to create an instance of the “Car” class.

ref class Car

{

public:

int doors;

int mpg; // miles per gallon

};

int main()

{

Car^ c1 = gcnew Car(); // instantiation

}

In reality, the instantiation takes two steps: declaration and creation. In order to create an

instance of a “reference” class, the class name must be followed by a caret sign (^) as a

“handle”. In Visual C++, a handle is a pointer to an object located on the Garbage Collection

heap. The following declares an instance c1 of the Car class, use:

Car^ c1;

The following statement demonstrates how to declare an instance of the “Student” class.

ref class Student { }

.......

Student^ s1; // declaration

Similar to the following statement that declares a variable named “x” of int type, the above

statement declares a variable named “s1” of the “Student” type.

int x;

A class declaration is only a type description; it does not actually create an object. Similar to

the following statement which instructs the computer to allocate a memory space to store the

value 15, programmers must issue a statement to instruct the computer to allocate memory

space for the “instance” of a “class” to use.

x = 15;

A “class” is said to be “abstract” because a class does not have any physical entity till an

object is declared and instantiated as its type. An “object” is said to be a physical

representation of the class that exists in memory. One analogy is to compare a “class” to a

blueprint of a building. A blueprint only illustrates the design plan with technical drawing, yet

it does not build anything. An “object” is one of the house that was built according to the

blueprint.

In Visual C++, memory for a managed type (reference or value type) is allocated by the

“gcnew” operator and deallocated by using garbage collection. The following bold-faced line

demonstrates how to “create” an “instance” after it has been declared as an “object” (named

“s1”) of the “Student” class. In other words, “s1” is “instantiated” as an object of the “Student”

class.

Page 6: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 227

ref class Student

{

..........

public:

Student() { }

.........

}

.......

Student^ s1; // declaration

s1 = gcnew Student(); // instantiation

As shown above, the “gcnew” operator calls the “default constructor” of the “Student” class.

In terms of object-oriented programming, a “constructor” is a “class method” of a special form

that is used by the compiler to create an “instance” of the class during the runtime. One

analogy to understand the role played by a “constructor” is to compare it to the construction

workers of a house-building project. While the architect draws the blueprint, the builder must

send construction workers to physically build the house.

Action Sample code House-building project

class definition ref class Student { }

draw the blueprint

instance

declaration

Student^ s1; approve to build the “s1”

unit of house

object creation s1 = gcnew Student(); launch the construction

The following demonstrates how to use the gcnew keyword to create an instance of the “Car”

class. Interestingly, the “gcnew” keyword can call either the “Car” class or its constructor to

create an instance of a managed type on the garbage collected heap. The follows call the

default constructor.

c1 = gcnew Car();

or, simply call the “Car” class and let the “Car” class calls its default constructor.

c1 = gcnew Car;

Often, programmers will declare and instantiate an instance in one single lien of statement, as

shown below.

Student^ s1 = gcnew Student();

Another example,

Car^ c1 = gcnew Car();

or,

Car^ c1 = gcnew Car;

A class is a data type; therefore, programmers can create an array of instance of a given class.

In other words, a C++ class can be instantiated as an array with every element of the array

using the class as data type. The following illustrates how to create an array of the “Car” class.

int main()

{

Page 7: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 228

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

}

The following is a sample class named “Rectangle”.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

ref class Rectangle

{

public:

int w, h;

Rectangle(int _w, int _h)

{

w = _w; h = _h;

}

};

The following a sample “main()” function that declare “rt” as an array of the “Rectangle”

class. In other words, “rt” uses “Rectangle” as data type. Each element of “rt” is an instance of

the “Rectangle” class with “rt[0]” being the first instance, “rt[1]” being the second instance,

and “rt[2]” being the third instance.

int main()

{

array<Rectangle^>^ rt = gcnew array<Rectangle^> (5);

rt[0] = gcnew Rectangle(5, 4);

rt[1] = gcnew Rectangle(6, 1);

rt[2] = gcnew Rectangle(3, 7);

rt[3] = gcnew Rectangle(9, 3);

rt[4] = gcnew Rectangle(8, 16);

}

In the following example, the instructor creates an array of the “State” class, and then uses a

while loop to repeatedly create three instances of the State class.

int main()

{

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.

int main()

Page 8: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 229

{

array <Telephone^>^ t = { gcnew Telephone(), gcnew Telephone(),

gcnew Telephone()};

}

Defining a class

method outside

the class

There is an interesting programming style that could possibly make the class body more

manageable. Some programmers prefer defining the methods of a class outside the class using

the scope resolution operator (::). When one class method contains lengthy contents, it is

probably a good idea to declare the method inside the class body but define the method outside

the class body. In the following example, all the member methods of the Rectangle class are

declared inside the class body; however, none of these member methods has definition of their

executions. In other words, they are empty methods.

ref class Rectangle

{

public:

float w, h, diagonal;

String^ getArea();

float getCircumference();

void getDiagonal();

};

The following demonstrates how to define the function of the “getArea()” method outside the

class body. In order to clearly specify that the “getArea()” method is a member of the

“Rectangle” class, it is necessary to use the scope resolution operator (::) with the format:

className::methodName().

String^ Rectangle::getArea()

{

return ("The area is " + w*h);

}

By the same token, the following demonstrates how to define the “getCircumference()”

method outside the class body. float Rectangle::getCircumference()

{

return (w+h)*2;

}

The following is the complete code that explains how this programming style works.

ref class Rectangle

{

public:

float w, h, diagonal;

String^ getArea();

float getCircumference();

void getDiagonal();

};

String^ Rectangle::getArea()

{

return ("The area is " + w*h);

}

Page 9: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 230

float Rectangle::getCircumference()

{

return (w+h)*2;

}

void Rectangle::getDiagonal()

{

diagonal = Math::Sqrt(w*w + h*h);

}

How to access

class members

from an object?

Only public members of a reference class can be accessed by its instance (which is known as

an object) using the access operator (->). The following illustrates the syntax to access a

“public” class variable.

objectID->variableName

In the following example, the “Rectangle” class contains two public variables: w an h. An

instance of the “Rectangle” class named “rt1” must access the w variable using rt1->w.

ref class Rectangle

{

.........

public:

float w, h;

........

};

int main()

{

Rectangle* rt1 = gcnew Rectangle();

rt1->w = 5.7;

rt1->h = 11.8;

..........

}

The following illustrates the syntax to access a member method.

objectID->methodName()

The following is a complete code that demonstrate how members of the “Car” class can be

used.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

ref class Car

{

public:

int doors;

int mpg; // miles per gallon

void mileage(); // member method

};

void Car::mileage()

{

MessageBox::Show(16 * mpg + "");

}

Page 10: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 231

int main()

{

Car^ c1 = gcnew Car(); // instantiation

c1->mpg = 27;

c1->doors = 2;

c1->mileage();

}

It is necessary to note that in native code (as well as C# and Java), the member access operator

is a dot (.) sign. In Visual C++ managed code, it must be ->.

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.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

ref class Car

{

public:

int doors;

int mpg; // miles per gallon

int mileage(); // member method that returns int

};

int Car::mileage()

{

return 16 * mpg;

}

int main()

{

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.");

}

Page 11: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 232

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.");

}

What is a

constructor?

In terms of object-oriented programming, a constructor is defined as a class member method

that will be automatically called for execution when an object is instantiated.

In a nutshell, all constructors of a class must have the same identifier with the class. For

instance, the default constructor of the “Student” class is “Student()”.

ref class Student

{

......

public: Student() { } // default constructor

......

}

In addition to creating an instance, constructors are also used to initialize member variables of

the class to appropriate default or user-provided values, or to do any setup steps necessary for

the class to be used properly. In the following example, the constructor “Student()” is also

used to set the value of the “gpa” variable.

ref class Student

{

private:

double gpa;

..........

Student() { gpa = 4.0; }

};

A default constructor is a constructor that either have no parameter, such as “Student()”. Any

Visual C++ class, with or without a programmer-defined default constructor, will be inserted a

default constructor by compiler. If the programmer chooses to define the default constructor,

then the programmer-defined one will override the compiler-inserted one. In the following

example, the “School” class does not have any default constructor. Yet, the compiler will

automatically insert one during the compilation. Therefore, programmer can use the “gcnew”

operator to call the “School()” constructor even though it is not defined inside the “School”

class.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

ref class School

{

public:

String^ schoolName;

int initalYear;

};

int main()

{

Page 12: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 233

School^ s1 = gcnew School();

s1->schoolName = "Cypress College";

s1->initalYear = 1957;

}

A class can have two or more constructors. Any constructor that takes one or more parameters,

such as Student(float g), are not the default constructor and can be called for execution

on demand.

ref class Student

{

private:

double gpa;

public:

......

Student() { gpa = 4.0; } //default constructor

Student(double g) { gpa=g; }; // constructor

};

The following is a sample “main()” function that can demonstrates how to call one of the

above constructors on demand. The “s1” object calls the “Student()” method without sending

any argument, while the “s2” object send 3.5 as argument to the “g” parameter. Therefore,

“s1” will be created using the default constructor, “Student()”, while “s2” will be created by

the constructor “Student(double g)”.

int main()

{

Student^ s1;

s1 = gcnew Student();

s1->firstName = "Jennifer";

Student^ s2;

s2 = gcnew Student(3.5);

s2->firstName = "Stephanie";

}

Constructors are not regular “class methods”. Regular “class methods” are defined for use only

after an instance is created, while “constructors” are the ones that create the instances. The

following defines a class of “ref” (reference) type named “Circle”. There is one “class

variables”, r, of float type which will keep the value of the radius of a circle. There is one class

member, PI, which is defined as a constant of float type to represent the mathematical symbol

π. The “Circle” has two “constructors”: Circle() and Circle(float r). There are two

“class methods”: getCircumference() and getArea(). They are defined for the instance of the

“Circle” class to call on demand.

ref class Circle

{

private:

float r;

const float PI = 3.14125;

public:

Circle() { r = 1.0; } // default constructor

Circle(float r) { r = _r; } // constructor

float getCircumference() { return 2 * PI * r; } // method

Page 13: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 234

float getArea() { return PI * r * r; } // method

};

The following is a sample “main()” function that illustrates how to call the “class methods”

after an instance (like “c1” and “c2”) is created. The format is objectID->methodName(),

which “->” is known as “member access operators”. All members of “ref” type of class must

be accessed using the “->” operator.

int main()

{

String^ str = nullptr;

Circle^ c1 = gcnew Circle();

str += c1->getCircumference() + "\n";

str += c1->getArea() + "\n";

Circle^ c2 = gcnew Circle(14.6);

str += c2->getCircumference() + "\n";

str += c2->getArea() + "\n";

MessageBox::Show(str);

}

In the above example, “c1” is the object identifier and is an instance of the “Circle” class.

Therefore, “c1” is allowed to access all public members of the “Circle” class. A statement like

c1->getCircumference() is for the “c1” object to call the “getCircumference()” method of

the “Circle” class.

Another “irregularity” of class constructors is that constructors cannot be called by the

instance. In the following, the “c1” object as an instance of the “Circle” class cannot call the

constructor of the class.

int main()

{

Circle^ c1 = gcnew Circle();

c1->Circle();

}

What is a

destructor?

In terms of object-oriented, a destructor is a special member function (known as method) that

is called for execution when the lifespan of an object ends. Typically, the lifespan of an object

will be forced to end when the program is terminated. The purpose of the destructor is to free

the resources that the object may have acquired during its lifespan. Destructors have the same

identifier as the class, except that they are preceded by a '~' operator. The following compares

the format of a constructor and a destructor of the “Student” class.

constructor destructor Student() { } ~Student() { }

The following demonstrates how to add a destructor to a “reference” class.

ref class Student

{

private:

double gpa;

public:

String^ firstName;

Student() { } //default constructor

Page 14: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 235

~Student() { } //destructor

};

The following is another example. It also demonstrates the use of the “delete” operator.

ref class myClass

{

private:

int x; // member field

int y; // member field

public:

myClass() //Constructor

{

x = 1;

y = 2;

}

~myClass() { } //destructor

};

int main()

{

myClass^ m1 = gcnew myClass();

delete m1; // destroy 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;

Interesting, one benefits of using managed type is that the “management” mechanism will

automatically release the acquired resources on program destruction. Therefore, whether or not

to add a destructor in a “reference” class is optional.

What are fields

and properties

of a class

In addition to methods and properties, object-oriented programming also allows programmers

to create constructors, and fields as members of a class. Fields are simply the class 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 creates three fields for the Telephone class: _make, _model, and _year. The

_year field 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.

Page 15: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 236

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:

public: property DataType PropertyName { }

Programmers should declare a property with the public modifier, so it can be used to store

data from code blocks outside the class. Programmers need to also declare property with

appropriate data type for 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

{

public: Telephone() { } // default constructor

//Fields

private: String^ _make;

private: String^ _model;

private: static String^ _year = "2016";

//property

public: 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 contain the “return”

keyword because it returns the value of 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.

Page 16: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 237

• A property with both get and set accessors is a read-write property.

For example,

// read-write property

public: property String^ Make

{

String^ get() { return _make; }

void set(String^ value) { _make = value; }

}

// write-only property

public: property String^ Model {

void set(String^ value) { _Model = value; }

}

// read-only property

public: property String^ Year

{

String^ get() { return _year; }

}

Similarly, the “Computer” class can be re-written to:

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

public ref class Computer // create a managed class

{

public: Computer() { }

private: String^ dimension;

private: String^ weight;

public: property String^ Dimension

{

String^ get() {return dimension;}

void set(String^ value) { dimension = value;}

}

public: 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.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

public ref class Computer // create a managed class

{

public: Computer() { }

Page 17: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 238

private: String^ dimension;

private: String^ weight;

public: String^ getDimension()

{

return dimension;

}

public: void setDimension(String^ _dimension)

{

dimension = _dimension;

}

};

int main()

{

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:

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

public ref class Computer // create a managed class

{

public: Computer() { }

private: String^ dimension;

private: String^ weight;

public: property String^ Dimension

{

String^ get() {return dimension;}

void set(String^ value) { dimension = value;}

}

public: property String^ Weight

{

String^ get() {return weight;}

void set(String^ value) { weight = value;}

}

};

int main()

{

Computer^ laptop = gcnew Computer;

laptop->Dimension = "24.5 x 15.9";

MessageBox::Show(laptop->Dimension);

}

User-created

header files

A well-defined class can be saved a header file or a library file; therefore, it can be “included”

in other Visual C++ source files. The following example breaks the above code into two

Page 18: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 239

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 #using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

ref class Car

{

public:

int doors;

int mpg; // miles per gallon

int total;

int mileage();

};

int Car::mileage()

{

total = 16 * mpg;

return total;

}

The 1.cpp file #include "car.h"

int main()

{

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"

int main()

{

Car c1;

c1.doors = 4;

c1.mpg = 35;

MessageBox::Show(c1.mileage()+"");

return 0;

}

The output looks:

560

Page 19: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 240

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"

int main()

{

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

{

..........

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);

};

Page 20: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 241

#include "states.cpp"

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

{

public:

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

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

{

public:

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.

Programmers cannot create an object of an abstract class type. If you attempt to do so, as

shown below, they will get a compiling error.

int main()

{

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'

In a tradtional C++ code, programmers can use pointers and references to abstract class types.

For example,

#include <iostream>

using namespace std;

class Shape

{

public:

virtual void drawShape() const = 0; // pure virtual function

};

class Rectangle : public Shape

Page 21: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 242

{

public:

virtual void drawShape() const {

cout << "Draw the shape!" << endl;

}

};

int main()

{

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.

ref class Shape { }

and

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,

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

ref class Shape

{

public:

virtual void drawShape() = 0; // pure virtual function

};

ref class Rectangle : public Shape

{

public:

virtual void drawShape() override {

MessageBox::Show( "Draw the shape!" );

}

};

int main()

{

Rectangle^ Rectangle1 = gcnew Rectangle;

Rectangle1->drawShape();

return 0;

}

Access modifier At the end of this lecture, the instructor believes it is necessary to revisit the concept of Access

modifiers. The Access modifiers determines the access to the names that follow it, up to the

Page 22: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 243

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.

public: 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 paradigm, hiding 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.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

ref class Apple

{

private: int x;

protected: int y;

public: int z;

};

int main()

{

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.

int main()

{

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”.

Page 23: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 244

int main()

{

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.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

ref class Student

{

private:

double gpa;

protected:

DateTime dt;

public:

String^ firstName;

String^ lastName;

void setGPA(int 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";

str += "Date: " + dt;

return str;

}

};

int main()

{

Student^ s1 = gcnew Student; // create an instance named s1

s1->firstName = "Jennifer";

s1->lastName = "Lopez";

s1->setGPA(3.6);

Page 24: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 245

MessageBox::Show(s1->printReport());

}

The output looks:

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

{

public:

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.

3. Given the following code segment, which is the method?

ref class myTest {

private:

int ID

public:

int getID() {

return ID;

}

}

A. myTest

B. ID

C. getID()

D. return

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();

Page 25: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 246

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. public: 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 public: class A { }

D. ref object A { int x; };

7. Which creates a destructor for a class named myTest?

A. private: ~myTest() { };

B. public: myTest() { };

C. public: desct myTest() { };

D. public: ~myTest() { };

8. Given the following code, which main() method will compile without error message?

ref class Apple {

private: int x;

protected: int y;

public: int z;

};

A. int main() { Apple^ a1 = gcnew Apple; a1->x = 5; a1->y = 3; }

B. int main() { Apple^ a1 = gcnew Apple; a1->x = 5; a1->z = 2; }

C. int main() { Apple^ a1 = gcnew Apple; a1->y = 3; a1->z = 2; }

D. int main() { 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() { }

public: void findMax() { }

protected: void findSum() { }

static void findAvg() { }

};

int main()

{

Apple^ a1 = gcnew Apple();

}

A. a1->findMin();

B. a1->findMax();

C. a1->findSum();

D. a1->findAvg();

10. Given the following code, the output is __.

#using <System.dll>

#using <System.Windows.Forms.dll>

Page 26: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 247

using namespace System;

using namespace System::Windows::Forms;

ref class myClass

{

public:

int x;

void set_values(int i)

{

x = i;

}

int my() {

return (x * 3);

}

};

int main() {

myClass^ a = gcnew myClass;

a->set_values(6);

MessageBox::Show(a->my() + "");

}

A. 18

B. a.my()

C. 6 * 3

D. i * 3

Page 27: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 248

Lab #8 Object-Oriented Programming

Learning Activity #1: A simple class

1. Create a directory called C:\cis223 if necessary.

2. Make sure the “InputBox.cpp” file (you created in Lab #1) is in the C:\cis223 directory.

3. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223

directory.

4. Use Notepad to create a new file named lab8_1.cpp with the following contents:

#include "InputBox.cpp"

ref class Circle

{

private:

// class variables

float r;

const float PI = 3.14125;

public:

// constructors

Circle() { r = 1.0; } // default constructor

Circle(float _r) { r = _r; } // regular constructor

// class methods

float getArea() { return PI * r * r; }

float getCircumference() { return 2 * PI * r; }

};

int main()

{

String^ str = "Area\tCircumference\n";

Circle^ c1 = gcnew Circle(); // create an instance

str += c1->getArea() + "\t";

str += c1->getCircumference() + "\n";

Circle^ c2 = gcnew Circle(14.6);

str += c2->getArea() + "\t";

str += c2->getCircumference() + "\n";

Circle^ c3 = gcnew Circle(Convert::ToSingle(InputBox::Show("Enter the radius:")));

str += c3->getArea() + "\t";

str += c3->getCircumference() + "\n";

MessageBox::Show(str);

}

5. Open the Visual Studio (2010) Command Prompt, type cl /clr lab8_1.cpp /link

/subsystem:windows /ENTRY:main and press [Enter] to compile. The output looks:

Page 28: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 249

and

6. Download the “assignment template” and rename it to lab8.doc if necessary. Capture a screen shot similar to the

above figure and paste it to the Word document named lab8.doc (or .docx).

Learning Activity #2:

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 lab8_2.cpp with the following contents:

#include "InputBox.cpp"

ref class Student

{

private:

double gpa;

protected:

DateTime dt;

public:

String^ firstName;

String^ lastName;

void setGPA(double g)

{

gpa = g;

}

double getGPA()

{

return gpa;

}

String^ printReport()

{

String^ str = "Name: " + firstName + " " + lastName + "\n";

str += "GPA: " + getGPA() + "\n\n";

return str;

}

};

int main()

{

String^ isContinued = "Y"; // should the while loop continue??

Student^ s1 = gcnew Student; // create an instance named s1

String^ result = "Date: " + DateTime::Now + "\n";

result += "------------Report------------\n";

while (isContinued == "Y")

{

s1->firstName = InputBox::Show("First Name: ");

s1->lastName = InputBox::Show("Last Name: ");

s1->setGPA(Convert::ToDouble(InputBox::Show("GPA: ")));

Page 29: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 250

result += s1->printReport();

isContinued = InputBox::Show("Do you want to continue? [Y/N]:");

// take only 1st letter if given two or more

isContinued = isContinued->Substring(0,1);

// convert the letter to uppercase

isContinued = isContinued->ToUpper();

}

MessageBox::Show(result);

}

3. Compile and test the program. The output looks:

4. Capture a screen shot similar to the above figure and paste it to the Word document named lab8.doc (or .docx).

Learning Activity #3:

1. Under the C:\cis223 directory, use Notepad to create a new file named car.cpp with the following contents. The

objective is to make this “.cpp” file a supportive library for other “.cpp” file to use.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

public ref class Car // or simply ref class Car

{

public:

String^ Make;

String^ Model;

double msrp;

String^ OutOfDoorPrice(double tax); // member method

};

String^ Car::OutOfDoorPrice(double tax)

{

return (tax * msrp) + "";

}

Page 30: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 251

2. Create another new file named lab8_3.cpp with the following contents. This file will import all the source code

from the “library” file.

#include "car.cpp"

int main()

{

String^ str = "--------------------REPORT-------------------\n";

str += "Make\tModel\tMSRP\tPrice\n";

array <Car^>^ c = gcnew array <Car^> (3); // array of Car

c[0] = gcnew Car;

c[0]->Make = "Toyota";

c[0]->Model = "Avalon";

c[0]->msrp = 32570.95;

c[1] = gcnew Car;

c[1]->Make = "Nissan";

c[1]->Model = "Maximum";

c[1]->msrp = 26165.50;

c[2] = gcnew Car;

c[2]->Make = "Subura";

c[2]->Model = "Legacy";

c[2]->msrp = 22840.75;

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);

}

3. Compile and test the program.

4. Capture a screen shot similar to the above figure and paste it to the Word document named lab8.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 lab8_4.cpp with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

public ref class Telephone // or simply ref class Telephone

{

public: Telephone() { } // default constructor

//Fields

Page 31: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 252

private: String^ _make;

private: String^ _model;

private: static String^ _year = "2026";

// read-write property

public: property String^ Make

{

String^ get() { return _make; }

void set(String^ value) { _make = value; }

}

// write-only property

public: property String^ Model

{

void set(String^ value) { _model = value; }

}

// read-only property

public: property String^ Year

{

String^ get() { return _year; }

}

public: String^ showModel() // a function that return _model value

{

return _model; // because Model does not return value

}

};

int main()

{

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 lab8.doc (or .docx).

Page 32: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 253

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 lab8_5.cpp with the following contents:

#include "InputBox.cpp"

public ref class State // or simply ref class State

{

private: // fields

String^ st;

String^ stFullName;

public:

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

int main()

{

String^ str = "Abbr\tState\n";

array <State^>^ s = gcnew array<State^> (3);

int i=0;

while (i<3)

{

// pass the user input to a constructor

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.

Page 33: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 254

4. Test the program few times to see how random number can produce different the results.

and and and

5. Capture a screen shot similar to the above figure and paste it to the Word document named lab8.doc (or .docx).

Submittal

1. Complete all the 5 learning activities and the programming exercise in this lab.

2. Create a .zip file named lab8.zip containing ONLY the following self-executable files.

• lab8_1.exe

• lab8_2.exe

• lab8_3.exe

• lab8_4.exe

• lab8_5.exe

• lab8.doc (or lab8.docx or .pdf) [You may be given zero point if this Word document is missing]

3. Log in to course web site (e.g. Canvas or Blackboard) and enter the course site.

4. Upload the zipped file to Question 11 of Assignment 07 as response.

Programming Exercise 08:

1. Launch the Developer Command Prompt.

2. Use Notepad to create a new text file named ex08.cpp.

3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one).

//File Name: ex08.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 0.83

6. 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 1.25

7. 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.

Page 34: Term Object-Oriented Paradigm Real-life examplestudents.cypresscollege.edu/cis223/lc08.pdf · Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation,

Visual C++ Programming – Penn Wu, PhD 255

9. Display the result in a message box. A sample output looks:

10. Compile the source code to produce executable code.

11. Download the “programming exercise template” and rename it to ex08.doc if necessary. Copy your source

code to the file and then capture the screen shot(s) similar to the above one and paste it to the Word document

named “ex08.doc” (or .docx).

12. Compress the source file (ex08.cpp), executable code (ex08.exe), and Word document (ex08.doc) to a .zip file

named “ex08.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 not true object-oriented language. If this argument is

true, then, 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.