OOP TutorialQuestion2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

CMP2005 – Object-Oriented Programming

Assignment #2 – Answer Key

1. What is the difference between protected and private members?

Answer:
A private member is inaccessible from anywhere outside its class definition. A protected
member is inaccessible from anywhere outside its class definition, with the exception that it is
accessible from the definitions of derived classes.

2. How do the default constructors and destructors behave in an inheritance hierarchy?

Answer:
In an inheritance hierarchy, each default constructor invokes its parent’s default constructor
before it executes itself, and each destructor invokes its parent’s destructor after it executes
itself. The effect is that all the parent default constructors execute in top-down order, and all
the parent destructors execute in bottom-up order.

3. Consider the following base and derived classes and according to class access specifier, list
class members access specifications.

i. public (public Grade)


ii. protected (protected Grade)
iii. private (private Grade)
Answer:

i. public Grade:

ii. protected Grade


iii. private Grade

4. Consider the following declaration and answer the questions given below:
i. Name the base class and derived class of the class QQQ.
ii. Name the data member(s) that can be accessed from function disp().
iii. Name the member function(s), which can be accessed from the objects of class RRR.
iv. Is the member function out() accessible by the object of the class QQQ?
Answer:
i. base class – PPP
derived class – RRR

ii. M, U

iii. disp(), indata(), outdata()

iv. No.

5. Answer the questions (i) to (iv) based on the following:


i. Write the names of data members, which are accessible from objects belonging to class
Author.
ii. Write the names of all the member functions which are accessible from objects belonging to
class Branch.
iii. Write the names of all the members which are accessible from member functions of class
Author.
iv. How many bytes will be required by an object belonging to class Author?
Answer:

i. None

ii. haveit(), giveit()

iii. member functions :


 register(), enter(), display(), haveit(),
 giveit(), start(), show()
 data members :
 employees, acode, aname, amount

iv. 72

6. Consider the following declarations and answer the question given below:
i. Name the base class and derived class of the class Heavyvehicle.
ii. Name the data member(s) that can be accessed from function displaydata().
iii. Name the data member's that can be accessed by an object of Bus class.
iv. Is the member function outputdata() accessible to the objects of Heavyvehicle class.

Answer:

i. base class – Vehicle


derived class – Bus

ii. passenger, load, make

iii. None

iv. No
7. Answer the questions (i) to (iv) based on the following code:
i. Write names of all the data members which are accessible from the object of class
PainReliever.
ii. Write names of all the members accessible from member functions of class Tablet.
iii. Write names of all the member functions which are accessible from objects of class
PainReliever.

Answer:

i. price
ii. Data Members:
tablet_name, volume_label, price
Member Functions:

enterdrugdetails(), showdrugdetails(),
entertabletdetails(), showtabletdetails()

iii. enterdrugdetails(),showdrugdetails(), entertabletdetails(),


showtabletdetails (), enterdetails(), showdetails()
8. Trace and provide the output of the following programs. In addition, explain the programs in
few sentences.

(i) Program 1:

#include <iostream>
using namespace std;

//********************************
// BaseClass declaration *
//********************************

class BaseClass
{
public:
BaseClass() // Constructor
{ cout << "This is the BaseClass constructor.\n"; }

~BaseClass() // Destructor
{ cout << "This is the BaseClass destructor.\n"; }
};

//********************************
// DerivedClass declaration *
//********************************

class DerivedClass : public BaseClass


{
public:
DerivedClass() // Constructor
{ cout << "This is the DerivedClass constructor.\n"; }

~DerivedClass() // Destructor
{ cout << "This is the DerivedClass destructor.\n"; }
};

//********************************
// main function *
//********************************

int main()
{
cout << "We will now define a DerivedClass object.\n";

DerivedClass object;

cout << "The program is now going to end.\n";


return 0;
}

Answer:
We will now define a DerivedClass object.
This is the BaseClass constructor.
This is the DerivedClass constructor.
This is the DerivedClass destructor.
This is the BaseClass destructor.
The program is now going to end.

(ii) Program 2:

Rectangle.h
////////////////////////////////////////////////////////
class Rectangle
{
private:
double width;
double length;
public:
// Default constructor
Rectangle()
{ width = 0.0;
length = 0.0; }

// Constructor #2
Rectangle(double w, double len)
{ width = w;
length = len; }

double getWidth() const


{ return width; }

double getLength() const


{ return length; }

double getArea() const


{ return width * length; }
};
/////////////////////////////////////////////////////

Box.h:
////////////////////////////////////////////////////////
class Box : public Rectangle
{
protected:
double height;
double volume;
public:
// Default constructor
Box() : Rectangle()
{ height = 0.0; volume = 0.0; }

// Constructor #2
Box(double w, double len, double h) : Rectangle(w, len)
{ height = h;
volume = getArea() * h; }

double getHeight() const


{ return height; }

double getVolume() const


{ return volume; }
};
////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
#include <iostream>
#include "Box.h"
using namespace std;

int main()
{
double boxWidth; // To hold the box's width
double boxLength; // To hold the box's length
double boxHeight; // To hold the box's height

// Get the width, length, and height from the user.


cout << "Enter the dimensions of a box:\n";
cout << "Width: ";
cin >> boxWidth;
cout << "Length: ";
cin >> boxLength;
cout << "Height: ";
cin >> boxHeight;

// Define a Box object.


Box myBox(boxWidth, boxLength, boxHeight);

// Display the Box object's properties.


cout << "Here are the box's properties:\n";
cout << "Width: " << myBox.getWidth() << endl;
cout << "Length: " << myBox.getLength() << endl;
cout << "Height: " << myBox.getHeight() << endl;
cout << "Base area: " << myBox.getArea() << endl;
cout << "Volume: " << myBox.getVolume() << endl;
return 0;
}
////////////////////////////////////////////////////////

Answer:
Enter the dimensions of a box:
Width: 10
Length: 10
Height: 10
Here are the box's properties:
Width: 10
Length: 10
Height: 10
Base area: 100
Volume: 1000

9. PersonData and CustomerData Classes

Design a class named PersonData with the following member variables:

 lastName
 firstName
 address
 city
 state
 zip
 phone

Write the appropriate accessor and mutator functions for these member variables.
Next, design a class named CustomerData, which is derived from the PersonData class. The
CustomerData class should have the following member variables:

 customerNumber
 mailingList

The customerNumber variable will be used to hold a unique integer for each customer. The
mailingList variable should be a bool. It will be set to true if the customer wishes to be on a
mailing list, or false if the customer does not wish to be on a mailing list. Write appropriate
accessor and mutator functions for these member variables. Demonstrate an object of the
CustomerData class in a simple program. In addition, draw the UML diagram for all of the
designed classes and also specify their relationship in the diagram.
Answer:

PersonData
- lastname : string
- firstname : string
- address : string
- city : string
- state : string
- zip : int
- phone : long
+ PersonData()
+ setLastName(lname : string) : void
+ setFirstName(fname : string) : void
+ setAddress(addr : string) : void
+ setCity(ct : string) : void
+ setState(st : string) : void
+ setZip(zp : string) : void
+ setPhone(ph : string) : void
+ getLastName() : string
+ getFirstName() : string
+ getAddress() : string
+ getCity() : string
+ getState() : string
+ getZip() : int
+ getPhone() : long

CustomerData
- customerNumber : long
- mailingList : bool

+ CustomerData()
+ setCustomerNumber(custNo : int) :
void
+ setMailingList(mlist : bool) : void
+ getCustomerNumber () : int
+ getMailingList () : bool
#include <iostream>
#include <string>
using namespace std;

class PersonData
{
private:
string lastName;
string firstName;
string address;
string city;
string state;
int zip;
long phone;

public:
PersonData()
{
lastName = "";
firstName = "";
address = "";
city = "";
state = "";
zip = 0;
phone = 0;
}

void setLastName(string lname)


{
lastName = lname;
}

void setFirstName(string fname)


{
firstName = fname;
}

void setAddress(string addr)


{
address = addr;
}

void setCity(string ct)


{
city = ct;
}
void setState(string st)
{
state = st;
}

void setZip(int zp)


{
zip = zp;
}

void setPhone(long ph)


{
phone = ph;
}

string getLastName()
{
return lastName;
}

string getFirstName()
{
return firstName;
}

string getAddress()
{
return address;
}

string getCity()
{
return city;
}

string getState()
{
return state;
}

int getZip()
{
return zip;
}

long getPhone()
{
return phone;
}
};

class CustomerData : public PersonData


{
private:
long customerNumber;
bool mailingList;

public:
CustomerData() : PersonData()
{
customerNumber = 0;
mailingList = false;
}

void setCustomerNumber(long custNo)


{
customerNumber = custNo;
}

void setMailingList(bool mlist)


{
mailingList = mlist;
}

long getCustomerNumber()
{
return customerNumber;
}

bool getMailingList()
{
return mailingList;
}
};

int main()
{

CustomerData cust1;

cust1.setLastName("Guney");
cust1.setFirstName("Huseyin");
cust1.setAddress("Nicosia");
cust1.setCity("Nicosia");
cust1.setState("Nicosia");
cust1.setZip(90000);
cust1.setPhone(12345678);
cust1.setCustomerNumber(1020304050);
cust1.setMailingList(1);

cout << "Details of Customer #1:" << endl;


cout << "Customer Number: " << cust1.getCustomerNumber() << endl;
cout << "First Name: " << cust1.getFirstName() << endl;
cout << "Last Name: " << cust1.getLastName() << endl;
cout << "Address: " << cust1.getAddress() << endl;
cout << "City: " << cust1.getCity() << endl;
cout << "State: " << cust1.getState() << endl;
cout << "Zip: " << cust1.getZip() << endl;
cout << "Phone: " << cust1.getPhone() << endl;
cout << "Registered to the Mailing List?: " << ((cust1.getMailingList() == 1) ? "Yes" :
"No") << endl;

return 0;
}

10. PreferredCustomer Class

A retail store has a preferred customer plan where customers may earn discounts on all their
purchases. The amount of a customer’s discount is determined by the amount of the
customer’s cumulative purchases in the store.

 When a preferred customer spends $500, he or she gets a 5 percent discount on all
future purchases.
 When a preferred customer spends $1,000, he or she gets a 6 percent discount on all
future purchases.
 When a preferred customer spends $1,500, he or she gets a 7 percent discount on all
future purchases.
 When a preferred customer spends $2,000 or more, he or she gets a 10 percent discount
on all future purchases.

Design a class named PreferredCustomer, which is derived from the CustomerData class you
created in the previous question. The PreferredCustomer class should have the following
member variables:

 purchasesAmount (a double)
 discountLevel (a double)

The purchasesAmount variable holds the total of a customer’s purchases to date. The
discountLevel variable should be set to the correct discount percentage, according to the store’s
preferred customer plan. Write appropriate member functions for this class and demonstrate it
in a simple program.

Input Validation: Do not accept negative values for any sales figures.

Answer:

#include <iostream>
#include <string>
using namespace std;

class PersonData
{
private:
string lastName;
string firstName;
string address;
string city;
string state;
int zip;
long phone;

public:
PersonData()
{
lastName = "";
firstName = "";
address = "";
city = "";
state = "";
zip = 0;
phone = 0;
}

void setLastName(string lname)


{
lastName = lname;
}

void setFirstName(string fname)


{
firstName = fname;
}
void setAddress(string addr)
{
address = addr;
}

void setCity(string ct)


{
city = ct;
}

void setState(string st)


{
state = st;
}

void setZip(int zp)


{
zip = zp;
}

void setPhone(long ph)


{
phone = ph;
}

string getLastName()
{
return lastName;
}

string getFirstName()
{
return firstName;
}

string getAddress()
{
return address;
}

string getCity()
{
return city;
}

string getState()
{
return state;
}

int getZip()
{
return zip;
}

long getPhone()
{
return phone;
}
};

class CustomerData : public PersonData


{
private:
long customerNumber;
bool mailingList;

public:
CustomerData() : PersonData()
{
customerNumber = 0;
mailingList = false;
}

void setCustomerNumber(long custNo)


{
customerNumber = custNo;
}

void setMailingList(bool mlist)


{
mailingList = mlist;
}

long getCustomerNumber()
{
return customerNumber;
}

bool getMailingList()
{
return mailingList;
}
};

class PreferredCustomer : public CustomerData


{
private:
double purchasesAmount;
double discountLevel;

public:
PreferredCustomer() : CustomerData()
{
purchasesAmount = 0.0;
discountLevel = 0.0;
}

void setPurchasesAmount(double pAmount)


{
purchasesAmount = pAmount;
}

void setdiscountLevel(double dLevel)


{
discountLevel = dLevel;
}

double getPurchasesAmount()
{
return purchasesAmount;
}

double getDiscountLevel()
{
return discountLevel;
}

double CalcDiscountLevel()
{
if(purchasesAmount > 0)
{
if(purchasesAmount <= 500)
discountLevel = 0.05;
else if(purchasesAmount > 500 && purchasesAmount <=
1000)
discountLevel = 0.06;
else if(purchasesAmount > 1000 && purchasesAmount <=
1500)
discountLevel = 0.07;
else if(purchasesAmount > 2000)
discountLevel = 0.10;
else
cout << "Something is went wrong, start over!" <<
endl;
}
else
cout << "Something is went wrong, start over!" << endl;
}
};

int main()
{

PreferredCustomer cust1;

cust1.setLastName("Guney");
cust1.setFirstName("Huseyin");
cust1.setAddress("Nicosia");
cust1.setCity("Nicosia");
cust1.setState("Nicosia");
cust1.setZip(90000);
cust1.setPhone(12345678);
cust1.setCustomerNumber(1020304050);
cust1.setMailingList(1);

cout << "Details of Customer #1:" << endl;


cout << "Customer Number: " << cust1.getCustomerNumber() << endl;
cout << "First Name: " << cust1.getFirstName() << endl;
cout << "Last Name: " << cust1.getLastName() << endl;
cout << "Address: " << cust1.getAddress() << endl;
cout << "City: " << cust1.getCity() << endl;
cout << "State: " << cust1.getState() << endl;
cout << "Zip: " << cust1.getZip() << endl;
cout << "Phone: " << cust1.getPhone() << endl;
cout << "Registered to the Mailing List?: " << ((cust1.getMailingList() == 1) ?
"Yes" : "No") << endl;

cout << endl;


cout << "Enter all purchases of the customer 1 to calculate his/her discount level:"
<< endl;

int cnt = 1;
double purchAmount;
double TotpurchAmount = 0;

while (!(purchAmount == -1))


{
cout << "Enter purchase #" << cnt << "(To terminate the loop enter -1!)";
cin >> purchAmount;
TotpurchAmount = TotpurchAmount + purchAmount;
cnt++;
}

cout << endl;


cust1.setPurchasesAmount(TotpurchAmount);
cout << "Customer purchases total amount is $" << cust1.getPurchasesAmount()
<< endl;
cust1.CalcDiscountLevel();

cout << "Customer #1's discount level is: " << cust1.getDiscountLevel() * 100 <<
"%" << endl;

return 0;
}
11. Ship, CruiseShip, and CargoShip Classes

Design a Ship class that has the following members:

 A member variable for the name of the ship (string)


 A member variable for the year that the ship was built (a string)
 A constructor and appropriate accessors and mutators
 A virtual print function that displays the ship’s name and the year it was built.

Design a CruiseShip class that is derived from the Ship Class. The CruiseShip class should
have the following members:

 A member variable for the maximum number of passengers (an int)


 A constructor and appropriate accessors and mutators
 A print function that overrides the print function in the base class. The CruiseShip class’s
print function should display only the ship’s name and the maximum number of
passengers.
Design a CargoShip class that is derived from the Ship class. The CargoShip class should have
the following members:

 A member variable for the cargo capacity in tonnage (an int)


 A constructor and appropriate accessors and mutators
 A print function that overrides the print function in the base class. The CargoShip class’s
print function should display only the ship’s name and the ship’s cargo capacity.

Demonstrate the classes in a program that has an array of Ship pointers. The array elements
should be initialized with the addresses of dynamically allocated Ship, CruiseShip, and
CargoShip objects (See program 15-14, lines 17 through 22, for an example of how to do this).
The program should then step through the array, calling each object’s print function. In
addition, draw the UML diagram for all of the designed classes and also specify their
relationship in the diagram.
Answer:

UML Diagram:

Ship
- name : string
- madeYear : string

+ Ship()
+ Ship (n : string, my : string)
+ setName(n : string) : void
+ setMadeYear(my : string) : void
+ getName() : string
+ getMadeYear() : string

CruiseShip CargoShip
- maxPassCap : int - cargoCap : int

+ CruiseShip() + CargoShip()
+ CruiseShip (n : string, my : string, + CargoShip (n : string, my : string,
mpc : int) cc : int)
+ setMaxPassCap(mpc : int) : void + setCargoCap(cc : int) : void
+ getMaxPassCap() : int + getCargoCap() : int

Source Code:

#include <iostream>
#include <string>
using namespace std;

class Ship
{
private:
string name;
string madeYear;

public:
Ship()
{
name = "";
madeYear = "1980";
}

Ship(string n, string my)


{
name = n;
madeYear = my;
}

string getName()
{
return name;
}

string getMadeYear()
{
return madeYear;
}

void setName(string n)
{
name = n;
}

void setMadeYear(string my)


{
madeYear = my;
}

virtual void print()


{
cout <<"Ship Name: " << getName() << "\tShip Built Year: " <<
getMadeYear() << endl;
}
};

class CruiseShip : public Ship


{
private:
int maxPassCap;

public:
CruiseShip() : Ship()
{
maxPassCap = 0;
}

CruiseShip(string n, string my, int mpc)


{
maxPassCap = mpc;
setName(n);
setMadeYear(my);
}

int getMaxPassCap()
{
return maxPassCap;
}

void setMaxPassCap(int mpc)


{
maxPassCap = mpc;
}

virtual void print()


{
cout <<"Ship Name: " << getName() << "\tShip Built Year: " <<
getMadeYear() << endl;
}
};

class CargoShip : public Ship


{
private:
int cargoCap; //in tonnage

public:
CargoShip() : Ship()
{
cargoCap = 0;
}

CargoShip(string n, string my, int cc)


{
cargoCap = cc;
setName(n);
setMadeYear(my);
}

int getCargoCap()
{
return cargoCap;
}

void setCargoCap(int cc)


{
cargoCap = cc;
}

virtual void print()


{
cout <<"Ship Name: " << getName() << "\tShip Built Year: " <<
getMadeYear() << endl;
}
};

int main()
{
const int SHIPCNT = 4;

Ship *shipArr[SHIPCNT] =
{ new Ship("Ship1", "2000"),
new CargoShip("Ship2", "2010", 10),
new CruiseShip("Ship3", "2005", 100),
new CruiseShip("Ship4", "2015", 150),
};

for (int count = 0; count < SHIPCNT; count++)


{
cout << "Ship #" << (count + 1) << ":\n";
shipArr[count] -> print();
cout << endl;
}

return 0;
}
12. Pure Abstract Base Class Project
Define a pure abstract base class called BasicShape. The BasicShape class should have the
following members:

 Private Member Variable:


o area: A double used to hold the shape’s area.
 Public Member Functions:
o getArea: This function should return the value in the member variable area.
o calcArea: This function should be a pure virtual function.

Next, define a class named Circle. It should be derived from the BasicShape class. It should
have the following members:

 Private Member Variable:


o centerX: A long integer used to hold x coordinate of the circle’s center.
o centerY: A long integer used to hold y coordinate of the circle’s center.
o radius: a double used to hold the circle’s radius

 Public Member Functions:


o constructor: accepts values for centerX, centerY, and radius. Should call the
overridden calcArea function described below.
o getCenterX: returns the value in centerX.
o getCenterY: returns the value in centerY.
o calcArea: calculates the area of the circle (area = 3.14159 * radius * radius) and
stores the result in the inherited member area.

Next, define a class named Rectangle. It should be derived from the BasicShape class. It
should have the following members:

 Private Member Variable:


o width: A long integer used to hold the width of the rectangle.
o length: A long integer used to hold the length of the rectangle.

 Public Member Functions:


o constructor: accepts values for width and length. Should call the overridden
calcArea function described below.
o getWidth: returns the value in width.
o getLength: returns the value in length.
o calcArea: calculates the area of the rectangle (area = length * width) and stores the
result in the inherited member area.

After you have created these classes, create a program that defines a Circle object and a
Rectangle object. Demonstrate that each object properly calculates and reports its area.
Answer:

#include <iostream>
using namespace std;

class BasicShape
{
protected:
double area;

public:
double getArea()
{ return area; }

virtual void calcArea() = 0;


};

class Circle : public BasicShape


{
private:
long centerX;
long centerY;
double radius;

public:
Circle(long cx, long cy, double r)
{
centerX = cx;
centerY = cy;
radius = r;
calcArea();
}

double getCenterX()
{ return centerX; }

double getCenterY()
{ return centerY; }

virtual void calcArea()


{
area = 3.14159 * radius * radius;
}
};

class Rectangle : public BasicShape


{
private:
long width;
long length;

public:
Rectangle(long w, long l)
{
width = w;
length = l;
calcArea();
}

double getWidth()
{ return width; }

double getLength()
{ return length; }

virtual void calcArea()


{
area = length * width;
}
};

int main()
{
Circle CObj(1,2,10);
Rectangle RObj(5,10);

cout << "Area of the Circle Object: " << CObj.getArea() << endl;
cout << "Area of the Rectangle Object: " << RObj.getArea() << endl;

return 0;
}
End of the document. v.2020.Spring-01

You might also like