0% found this document useful (0 votes)
21 views20 pages

COS1512 Assignment03

The document contains an assignment for COS1512 that includes C++ code for a Student class, explanations of object-oriented programming concepts, and corrections to code fragments. It covers topics such as constructors, destructors, accessors, mutators, inheritance, and separate compilation. Additionally, it includes code for a PhoneCall class and its usage in a program that calculates total charges for phone calls.

Uploaded by

S'fiso Mzilikazi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views20 pages

COS1512 Assignment03

The document contains an assignment for COS1512 that includes C++ code for a Student class, explanations of object-oriented programming concepts, and corrections to code fragments. It covers topics such as constructors, destructors, accessors, mutators, inheritance, and separate compilation. Additionally, it includes code for a PhoneCall class and its usage in a program that calculates total charges for phone calls.

Uploaded by

S'fiso Mzilikazi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Shinga Sisanda 24718971 COS1512 assignment 03

Unique Number:160814

Question 1
#include<iostream>
#include<string>

using namespace std;

class Student
{
private:
string name;
int quiz1;
int quiz2;
int midtermExam;
int finalExam;

public:
//Default constructor
Student(){
name= " ";
quiz1=0;
quiz2=0;
midtermExam=0;
finalExam=0;
}

//Mutators (Setters)
void setName(string studentname){
name = studentname;
}

void setQuiz1(int marks){


quiz1 = marks;
}

void setQuiz2(int marks){


quiz2 = marks;
}

void setMidtermExam(int marks){


midtermExam = marks;
}

void setFinalExam(int marks){


finalExam = marks;
}

// Accessors (Getters)
string getName()const{
return name;
}

int getQuiz1()const{
return quiz1;
}

int getQuiz2()const{
return quiz2;
}

int getMidtermExam()const{
return midtermExam;
}
int getFinalExam()const{
return finalExam;
}

//Function that calculate the weighted average


double calculateAverage()const{
double quizAverage = (((quiz1/10.0)*100)+((quiz2/10.0)*100))/2 ;
double quizweight = quizAverage * 0.25;
double midtermWeight = midtermExam * 0.25;
double finalWeight = finalExam * 0.5;
return quizweight + midtermWeight + finalWeight;
}
};

int main(){
Student studentObj;

//Input the student's data


string name;
int quiz1, quiz2, midtermExam, finalExam;

cout<<"Enter a student name: ";


cin>>name;
studentObj.setName(name);

cout<<"Enter Quiz 1 marks: ";


cin>>quiz1;
studentObj.setQuiz1(quiz1);

cout<<"Enter Quiz 2 marks: ";


cin>>quiz2;
studentObj.setQuiz2(quiz2);

cout<<"Enter Midterm Exam marks: ";


cin>>midtermExam;
studentObj.setMidtermExam(midtermExam);

cout<<"Enter Final Exam marks: ";


cin>>finalExam;
studentObj.setFinalExam(finalExam);

//Output the student's data


cout<<"\nStudent Record: \n";
cout<<"Student name: "<<studentObj.getName()<<"\n";
cout<<"Quiz 1: "<<studentObj.getQuiz1()<<"\n";
cout<<"Quiz 2: "<<studentObj.getQuiz2()<<"\n";
cout<<"Midterm exam: "<<studentObj.getMidtermExam()<<"\n";
cout<<"Final exam: "<<studentObj.getFinalExam()<<"\n";
cout<<"weighted average: "<<studentObj.calculateAverage()<<"\n";

return 0;
}

Output of the program:


Question 2
(a) Public and private are used to control access to the parts of a class.
Public means anyone can use those parts, while private means only the class
itself can use them.

(b) A class is like a blueprint that defines what an object will be like. An
object is an actual thing created from that blueprint and can be used in your
program.

(c) To instantiate an object means to create an actual instance of a class in


your program, making it real and usable.

(d) A constructor is a special function in a class that runs automatically


when you create an object. Its job is to set up the object and give it initial
values.

(e) A default constructor gives an object basic initial values without needing
input. An overloaded constructor allows you to create an object with specific
starting values.

(f) A destructor is a function that runs when an object is no longer needed.


It cleans up, like releasing memory or closing files.

(g) An accessor is a function that lets you look at a private variable in a


class without changing it.

(h) A mutator is a function that allows you to change a private variable in a


class, usually with some checks.

(i) The scope resolution operator (::) is used when you want to define or
access something specific from a class, especially when there could be
confusion with other names.

(j) The scope resolution operator (::) is for class or namespace members,
while the dot operator (.) is used to access variables and functions of an
object you’ve created from a class.

(k) A member function belongs to a class and works with that class’s data. An
ordinary function doesn’t belong to any class and works independently.

(l) An abstract data type (ADT) is a type of data that focuses on what it does
(like adding or removing items) rather than how it does it.

(m) You create an ADT by defining what actions can be done with it, usually
through a class, without worrying about the internal details.

(n) ADTs have benefits like making your code more organized, easier to
understand, and reusable without changing how they work inside.
(o) Separate compilation means compiling parts of your program individually
instead of all at once. It’s like assembling a puzzle from smaller pieces.

(p) The advantage of separate compilation is that it saves time, makes large
programs easier to manage, and helps you reuse pieces of code in other
projects.

(q) A derived class is a class that’s based on another class (the base class).
It inherits everything from the base class but can also add its own features.

(r) Inheritance lets you reuse code from one class in another, making it
easier to extend or modify existing classes instead of starting from scratch.

Question 3
Explanation of what is wrong with the given code fragment:

1.In the line “PersonType family[20], newBaby(“Anny Dude”,20180912, “2


sept”);”,
-the object(newBaby) is initialized in the same line as an array(family), an
array in C++ programming language can not be initialized as same line with an
object. The syntax used here will couse acompilation error.

2.Across the line that says “family.birthday[5] = newBaby.birthday”,


-here on this code “family” is an array of the object “PersonType”, but this
line attempts to access “family.birthday[5]”. This is incorrect because
“family” is an array and “family[i]” should be used to access “PersonType”
object specifically, not the “birthday” of the entire array.

3.The line “family.birthday[5] = newBaby.birthday”,


-implies that “birthday” and “name” are arrys inside the “PersonType” class,
Which is not corrrect. Instead, they are individual strings in the
“personType” object. The elements like “family[i].birday” and “family[i].name”
should be accessed.

Corrected code:
#include<iostream>
#include<string>

using namespace std;

class PersonType
{
private:
string name;
int ID;
string birthday;

public:
PersonType(){
name=" ";
ID=0;
birthday=" ";
}
PersonType(string n, int id, string bd){
name=n;
ID=id;
birthday=bd;
}

string getName()const{
return name;
}
int getID()const{
return ID;
}
string getBirthday()const{
return birthday;
}
};

int main()
{
PersonType family[20];
PersonType newBaby("Anny Dube", 20180912, "2 Sept");

for (int i = 0; i < 20; i++){


if(family[i].getBirthday()==newBaby.getBirthday()){
cout<<family[i].getName()<< " Share a birthday with
"<<newBaby.getName();
}
}

return 0;
}
Question 4

#include <iostream>
using namespace std;

class Date {
private:
int theday;
int themonth;
int theyear;
int monthLength() const;

public:
Date() : theday(14), themonth(9), theyear(1752) {}
Date(int day, int month, int year) : theday(day), themonth(month),
theyear(year) {}
int getDay() const { return theday; }
int getMonth() const { return themonth; }
int getYear() const { return theyear; }

void setDay(int day) { theday = day; }


void setMonth(int month) { themonth = month; }
void setYear(int year) { theyear = year; }

Date& operator++();
Date& operator--();
bool operator<(const Date& d) const;

friend ostream& operator<<(ostream &out, const Date &d);


};

bool isLeapYear(int year){


return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int Date::monthLength() const {
switch (themonth) {
case 4: case 6: case 9: case 11:
return 30;
case 2:
return isLeapYear(theyear) ? 29 : 28;
default:
return 31;
}
}

Date& Date::operator++() {
theday++;
if (theday > monthLength()) {
theday = 1;
themonth++;
if (themonth > 12) {
themonth = 1;
theyear++;
}
}
return *this;
}

Date& Date::operator--() {
theday--;
if (theday < 1) {
themonth--;
if (themonth < 1) {
themonth = 12;
theyear--;
}
theday = monthLength();
}
return *this;
}

bool Date::operator<(const Date &d) const {


if (theyear < d.theyear) return true;
if (theyear > d.theyear) return false;
if (themonth < d.themonth) return true;
if (themonth > d.themonth) return false;
return theday < d.theday;
}

ostream& operator<<(ostream &out, const Date &d) {


static const char* MonthNames[] = {"", "January", "February", "March",
"April", "May", "June",
"July", "August", "September", "October",
"November", "December"};
out << d.theday << " " << MonthNames[d.themonth] << " " << d.theyear;
return out;
}

int main() {
// Declare a new Date object called d1 (default constructor)
Date d1;
cout << "Default date: " << d1 << endl;

// Change the date to 28 February 2000


d1.setDay(28);
d1.setMonth(2);
d1.setYear(2000);
cout << "Set date to 28 February 2000: " << d1 << endl;

// set this date forward by one day


++d1;
cout << "After forwarding by one day: " << d1 << endl;

// Change the date to 1 January 2002


d1.setDay(1);
d1.setMonth(1);
d1.setYear(2002);
cout << "Set date to 1 January 2002: " << d1 << endl;

// set date back by 1 day


--d1;
cout << "After setting back by one day: " << d1 << endl;

// Change the date to 31 December 2002


d1.setDay(31);
d1.setMonth(12);
d1.setYear(2002);
cout << "Set date to 31 December 2002: " << d1 << endl;

// Advance this date by one day


++d1;
cout << "After forwarding by one day: " << d1 << endl;

// Declare a second date object d2(1,1,2003)


Date d2(1, 1, 2003);
cout << "Second date: " << d2 << endl;

// Determine if d1 comes before d2


if (d1 < d2) {
cout << d1 << " comes before " << d2 << endl;
} else {
cout << d1 << " comes after " << d2 << endl;
}

return 0;
}

Output of the program

Question 5

Code for Main.cpp file:


#include <iostream>
#include <fstream>
#include "PhoneCall.h"

int main() {
std::string testNumber;
std::cout << "Enter the phone number to calculate total charges: ";
std::cin >> testNumber;

PhoneCall theCall(testNumber);

std::ifstream inFile("MyCalls.dat");
if (!inFile) {
std::cerr << "Error opening file!" << std::endl;
return 1;
}

PhoneCall currentCall;
float totalCharges = 0.0f;
int numberOfCalls = 0;
int longestCallLength = 0;
PhoneCall longestCall;

while (inFile >> currentCall) {


if (currentCall == theCall) {
totalCharges += currentCall.calcCharge();
numberOfCalls++;
if (currentCall.getLength() > longestCallLength) {
longestCallLength = currentCall.getLength();
longestCall = currentCall;
}
}
}

inFile.close();

std::cout << "Total amount spent on calls to " << testNumber << ": " <<
totalCharges << std::endl;
std::cout << "Number of calls to " << testNumber << ": " << numberOfCalls
<< std::endl;
if (numberOfCalls > 0) {
std::cout << "Longest call: " << longestCall << std::endl;
} else {
std::cout << "No calls made to " << testNumber << std::endl;
}

return 0;
}

Code for PhoneCall.cpp file:

#include "PhoneCall.h"

// Default constructor
PhoneCall::PhoneCall() : number(""), length(0), rate(0.0f) {}

// Overloaded constructor
PhoneCall::PhoneCall(const std::string& phoneNumber) : number(phoneNumber),
length(0), rate(0.0f) {}

// Destructor
PhoneCall::~PhoneCall() {
// No special action needed
}
// Accessor functions
std::string PhoneCall::getNumber() const {
return number;
}

int PhoneCall::getLength() const {


return length;
}

float PhoneCall::getRate() const {


return rate;
}

// Member function to calculate charge


float PhoneCall::calcCharge() const {
return length * rate;
}

// Overloaded equality operator


bool operator==(const PhoneCall &call1, const PhoneCall &call2) {
return call1.number == call2.number;
}

// Overloaded extraction operator


std::istream& operator>>(std::istream &in, PhoneCall &call) {
in >> call.number >> call.length >> call.rate;
return in;
}

// Overloaded insertion operator


std::ostream& operator<<(std::ostream &out, const PhoneCall &call) {
out << "Number: " << call.number << ", Length: " << call.length
<< ", Rate: " << call.rate << ", Charge: " << call.calcCharge();
return out;
}

Code for PhoneCall.h file:

#define PHONECALL_H

#include <iostream>
#include <string>

class PhoneCall {
private:
std::string number;
int length;
float rate;

public:

PhoneCall();
PhoneCall(const std::string& phoneNumber);

~PhoneCall();
std::string getNumber() const;
int getLength() const;
float getRate() const;

float calcCharge() const;

friend bool operator==(const PhoneCall &call1, const PhoneCall


&call2);
friend std::istream& operator>>(std::istream &in, PhoneCall &call);
friend std::ostream& operator<<(std::ostream &out, const PhoneCall &call);
};

#endif

The MyCall.cpp file

0123452347 12 3.50
0337698210 9 3.15
0214672341 2 1.75
0337698210 15 3.15
0442389132 8 1.75
0232189726 5 3.50
0124395623 6 3.50
0337698210 2 3.15
0337698210 5 3.15

The Output of the whole program:


Question 6

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>

using namespace std;

class Student {
private:
string name;
int quiz1;
int quiz2;
int midtermExam;
int finalExam;

public:
// Default constructor
Student() : name(" "), quiz1(0), quiz2(0), midtermExam(0), finalExam(0) {}

// Mutators (Setters)
void setName(string studentname) { name = studentname; }
void setQuiz1(int marks) { quiz1 = marks; }
void setQuiz2(int marks) { quiz2 = marks; }
void setMidtermExam(int marks) { midtermExam = marks; }
void setFinalExam(int marks) { finalExam = marks; }

// Accessors (Getters)
string getName() const { return name; }
int getQuiz1() const { return quiz1; }
int getQuiz2() const { return quiz2; }
int getMidtermExam() const { return midtermExam; }
int getFinalExam() const { return finalExam; }

// Function that calculates the weighted average


double calculateAverage() const {
double quizAverage = (((quiz1 / 10.0) * 100) + ((quiz2 / 10.0) * 100))
/ 2;
double quizWeight = quizAverage * 0.25;
double midtermWeight = midtermExam * 0.25;
double finalWeight = finalExam * 0.5;
return quizWeight + midtermWeight + finalWeight;
}

// Overload the stream extraction operator


friend istream& operator>>(istream& in, Student& student);

// Overload the stream insertion operator


friend ostream& operator<<(ostream& out, const Student& student);
};

// Overload the stream extraction operator


istream& operator>>(istream& in, Student& student) {
string name;
int quiz1, quiz2, midtermExam, finalExam;

// Read the whole line


getline(in, name);

if (name.empty()) {
return in; // End of file or empty line
}

// Parse the line into individual parts


stringstream ss(name);
ss >> name >> quiz1 >> quiz2 >> midtermExam >> finalExam;

student.setName(name);
student.setQuiz1(quiz1);
student.setQuiz2(quiz2);
student.setMidtermExam(midtermExam);
student.setFinalExam(finalExam);

return in;
}

// Overload the stream insertion operator


ostream& operator<<(ostream& out, const Student& student) {
out << "Student name: " << student.getName() << "\n";
out << "Quiz 1: " << student.getQuiz1() << "\n";
out << "Quiz 2: " << student.getQuiz2() << "\n";
out << "Midterm exam: " << student.getMidtermExam() << "\n";
out << "Final exam: " << student.getFinalExam() << "\n";
out << "Weighted average: " << student.calculateAverage() << "\n";
return out;
}

const int MAX_STUDENTS = 20;

int main() {
Student students[MAX_STUDENTS];
int count = 0;

ifstream inFile("Student.dat");
if (!inFile) {
cerr << "Error opening file!" << endl;
return 1;
}

string line;
while (getline(inFile, line) && count < MAX_STUDENTS) {
stringstream ss(line);
Student tempStudent;
if (ss >> tempStudent) {
students[count++] = tempStudent;
} else {
cerr << "Error processing line: " << line << endl;
}
}
inFile.close();

if (count == 0) {
cerr << "No student data available." << endl;
return 1;
}

double totalAverage = 0;

cout << fixed << setprecision(2);

for (int i = 0; i < count; ++i) {


cout << students[i] << endl;
totalAverage += students[i].calculateAverage();
}

if (count > 0) {
cout << "Class average: " << (totalAverage / count) << endl;
}

return 0;
}

Question 7

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

class Student {
protected:
string name;
string studentNumber;
string address;
string degree;
public:
Student(string n, string sn, string addr, string deg)
: name(n), studentNumber(sn), address(addr), degree(deg) {}

string getName() const { return name; }


string getStudentNumber() const { return studentNumber; }
string getAddress() const { return address; }
string getDegree() const { return degree; }

friend ostream& operator<<(ostream& os, const Student& s) {


os << "Name: " << s.name << endl
<< "Student Number: " << s.studentNumber << endl
<< "Address: " << s.address << endl
<< "Degree: " << s.degree << endl;
return os;
}

virtual double calcFee() const {


if (degree[0] == 'B')
return 500;
return 600;
}
};
class PostgradStd : public Student {
private:
string dissertation;

public:
PostgradStd(string n, string sn, string addr, string deg, string diss)
: Student(n, sn, addr, deg), dissertation(diss) {}

string getDissertation() const { return dissertation; }

friend ostream& operator<<(ostream& os, const PostgradStd& ps) {


os << "Name: " << ps.name << endl
<< "Student Number: " << ps.studentNumber << endl
<< "Address: " << ps.address << endl
<< "Degree: " << ps.degree << endl
<< "Dissertation: " << ps.dissertation << endl;
return os;
}

double calcFee() const override {


return 600 + 12000; // Base postgraduate fee + additional fee
}
};

int main() {
// Test class Student
cout << "Testing Student class:" << endl;
Student s("Mary Mbeli", "12345678", "Po Box 16, Pretoria, 0818", "BSc");

//accessors to display details


cout << "Using Accessors:" << endl;
cout << "Name: " << s.getName() << endl;
cout << "Student Number: " << s.getStudentNumber() << endl;
cout << "Address: " << s.getAddress() << endl;
cout << "Degree: " << s.getDegree() << endl;

// display_info function (overloaded << operator)


cout << "\nUsing display_info (<< operator):" << endl;
cout << s;

// Calculate and display registration fee


cout << "Registration Fee: R" << s.calcFee() << endl;

// Test class PostgradStd


cout << "\nTesting PostgradStd class:" << endl;
PostgradStd ps("Mary Mbeli", "12345678", "Po Box 16, Pretoria, 0818",
"PhD", "How to get a PhD");

// accessors to display details


cout << "Using Accessors:" << endl;
cout << "Name: " << ps.getName() << endl;
cout << "Student Number: " << ps.getStudentNumber() << endl;
cout << "Address: " << ps.getAddress() << endl;
cout << "Degree: " << ps.getDegree() << endl;
cout << "Dissertation: " << ps.getDissertation() << endl;

cout << "\nUsing display_info (<< operator):" << endl;


cout << ps;

// Calculate and display registration fee


cout << "Registration Fee: R" << ps.calcFee() << endl;

return 0;
}

Output of the program:

You might also like