logical error using copy constructor in c++ - c++

In the following program my intended output is to display the list of item a customer object is interested of but it is showing null values. no values are printed when i am calling showitem(). please help me out to correct the logical fault in my code.
class item
{
int itemno;
string name;
public:
item()
{
itemno=0;
}
item(int r,string n)
{
itemno = r;
name = n;
}
void showitem()
{
cout<<"Item no is:"<<itemno<<"\n";
cout<<"Name is :"<<name<<"\n";
}
};
class customer
{
public:
int customerno;
string customername;
string address;
int totalitem;
item *iteminterested;
customer()
{
iteminterested=0;
totalitem=0;
}
customer(customer &custref)
{
customerno=custref.customerno;
customername=custref.customername;
address=custref.address;
iteminterested=new item[custref.totalitem];
for(int i=0;i<custref.totalitem;++i)
{
iteminterested[i]=custref.iteminterested[i];
}
totalitem=custref.totalitem;
}
customer(int no,string cusname,string add,item *temp,int total)
{
customerno=no;
customername=cusname;
address=add;
iteminterested=new item[total];
for(int i=0;i<totalitem;++i)
{
iteminterested[i]=temp[i];
}
totalitem=total;
}
void showcustomer()
{
cout<<"customer name is"<<customername<<"\n";
cout<<"customer number is"<<customerno<<"\n";
cout<<"customer address is"<<address<<"\n";
cout<<"customer " <<customername <<"intersted in \n";
for(int k=0;k<totalitem;k++)
{
iteminterested[k].showitem();
}
}
};
int main()
{
customer steve;
item itemarray[]={item(3,"sandwiches"),item(4,"paperbags"),item(5,"biscuits"),item(6,"coke"),item(10,"biscuits"),item(9,"pen"),item(1,"pencil"),item(2,"eraser")};
steve=customer(2,"steve","aus",itemarray,5);
steve.showcustomer();
customer mark(steve);
mark.showcustomer();
mark.showcustomer();
steve.showcustomer();
return 0;
}

In the customer constructor you must set totalitem before assigning the items. It is not initialized for the loop. Or use total for the loop.

#include <iostream>
#include <string>
using namespace std;
class Item {
int itemno;
string name;
public:
Item()
: itemno(0) { }
Item(int r, string n)
: itemno(r),
name(n) { }
void showitem() const {
cout << "Item no is: " << itemno << "\n";
cout << "Name is: " << name << "\n"; } };
class Customer {
public:
int customerno;
string customername;
string address;
int totalitem;
Item* iteminterested;
Customer()
: totalitem(0),
iteminterested(0) { }
Customer(const Customer& custref)
: customerno(custref.customerno),
customername(custref.customername),
address(custref.address),
totalitem(custref.totalitem) {
iteminterested = new Item[totalitem];
for (int i = 0; i < totalitem; ++i) {
iteminterested[i] = custref.iteminterested[i]; } }
Customer(int no, string cusname, string add, Item* temp, int total)
: customerno(no),
customername(cusname),
address(add),
totalitem(total) {
iteminterested = new Item[total];
for (int i = 0; i < totalitem; ++i) {
iteminterested[i] = temp[i]; } }
void showcustomer() const {
cout << "customer name is: " << customername << "\n";
cout << "customer number is: " << customerno << "\n";
cout << "customer address is: " << address << "\n";
cout << "customer " << customername << " intersted in \n";
for (int k = 0; k < totalitem; ++k) {
iteminterested[k].showitem(); } } };
int main() {
Customer steve;
Item itemarray[] = {
Item(3, "sandwiches"),
Item(4, "paperbags"),
Item(5, "biscuits"),
Item(6, "coke"),
Item(10, "biscuits"),
Item(9, "pen"),
Item(1, "pencil"),
Item(2, "eraser") };
steve = Customer(2, "steve", "aus", itemarray, 5);
steve.showcustomer();
Customer mark(steve);
mark.showcustomer();
mark.showcustomer();
steve.showcustomer();
return 0; }

Related

Error while using pointers and new operators in C++(Microsoft VS)

i was using pointers and new operator for printing different city names. But the Microsoft Visual Studio show that it is Exception thrown:read access violation.
This happen even when i write *ptr=n; or *ptr=20; ,but works properly if i give ptr=&n; (if n is the variable with some value).
Program to display names of cities
#include <iostream>
#include <cstring>
using namespace std;
class city
{
protected:
char *name;
int len;
public:
char *s;
city();
~city();
void getdata()
{
s = new char[20];
cout << "enter the name of city" << endl;
cin >> s;
len = strlen(s);
name = new char[len + 1];
strcpy_s(name, 10, s);
}
void display()
{
cout << *name << endl;
}
private:
};
city::city()
{
len = 0;//initialization
name = NULL;
}
city::~city()
{
delete[]name;
delete[]s;
}
int main()
{
city *obj[10];
int n = 0;
int en=0;
do
{
obj[n] = new city;
obj[n]->getdata();
n++;
obj[n]->display();
cout << "do you want to enter another city?" << endl;
cout << "(enter 1 for yes and 0 for no"<<endl;
cin >> en;
} while (en);
delete[]obj;
system("pause");
return 0;
}
Screenshot of error
Don't manage memory manually! Use STL to forget memory manage!
#include <iostream>
#include <string>
#include <array>
class city
{
protected:
std::string name;
public:
city() = default;
//~city();
void getdata()
{
std::cout << "enter the name of city" << std::endl;
std::cin >> this->name;
}
void display()
{
std::cout << name << std::endl;
}
};
int main()
{
std::array<city, 10> obj;
for(auto&& o : obj)
{
o.getdata();
o.display();
std::cout
<< "do you want to enter another city?" << std::endl
<< "(enter 1 for yes and 0 for no" << std::endl;
int en=0;
std::cin >> en;
if(0 == en) return 0;
}
return 0;
}
https://wandbox.org/permlink/bz4iF3LNDSyUIZPb

Implementing a quicksort algorithm for a vector of objects

I was given an assignment to implement a quicksort algorithm into my C++ program. The homework is a part of series which started with objects and inheritance, but our lector didn't really explain quicksort to us.
However, I can't really understand how do I select the vector of an object that is to be sorted and how do I set the low and high limits.
Here is the code
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <functional>
using namespace std;
template <typename T> T AskFor(string text) {
cout << text << endl;
T result;
cin >> result;
cin.clear();
return result;
}
class Vehicle {
public:
Vehicle(string producer, string model, int year)
: model(model) {
setProducer(producer);
setYear(year);
}
void output() {
cout << " producer(vehicle): " << producer << endl;
cout << " model(vehicle): " << model << endl;
cout << " year(vehicle): " << year << endl;
}
void setProducer(const string producer) {
if (isProducerValid(producer)) {
this->producer = producer;
}
}
string getProducer() const {
return producer;
}
void setModel(const string model) {
this->model = model;
}
string getModel() const {
return model;
}
void setYear(const int year) {
if (isYearValid(year)) {
this->year = year;
}
}
int getYear() const {
return year;
}
static bool isYearValid(int year) {
return year >= 1950 && year <= 2016;
}
static bool isProducerValid(string producer) {
static string PRODUCERS[] { "Toyota", "Audi", "BMW", "Mercedes" };
return find(begin(PRODUCERS), end(PRODUCERS), producer) != end(PRODUCERS);
}
private:
string producer;
string model;
int year;
};
class Vendor {
public:
Vendor(string v_name, string address, string phone, vector<string> delivery)
: v_name(v_name),
address(address),
delivery(delivery) {
setPhone(phone);
}
void setVendorName(const string v_name) {
this->v_name = v_name;
}
string getVendorName() const {
return v_name;
}
void setAddress(const string address) {
this->address = address;
}
string getAddress() const {
return address;
}
void setPhone(const string phone) {
this->phone = phone;
}
string getPhone() const {
return phone;
}
void setDelivery(const vector<string> delivery) {
this->delivery = delivery;
}
vector<string> getDelivery() const {
return delivery;
}
static bool isPhoneNumber(string phone) {
if (phone.empty()) {
return false;
}
return all_of(begin(phone), end(phone), isdigit);
}
private:
string v_name;
string address;
string phone;
vector<string> delivery;
};
class SparePart {
public:
SparePart(string id, string name, Vehicle* v, int price, int time_to_replace,
bool is_new = true, string description = "", string manual = "")
: id(id),
name(name),
vehicle(v),
price(price),
time_to_replace(time_to_replace),
is_new(is_new),
description(description),
manual(manual) {}
double replacementPrice() {
return price + time_to_replace * 20;
}
int warranty() const {
return is_new ? 36 : 3;
}
virtual void output() {
cout << " ID: " << id << endl;
cout << " name: " << name << endl;
vehicle->output();
if (is_new) cout << " new" << endl;
else {
cout << " recycled" << endl;
}
cout << " description: " << description << endl;
cout << " manual: " << manual << endl;
}
virtual ~SparePart() = 0;
void setId(const string id) {
this->id = id;
}
string getId() const {
return id;
}
void setName(const string name) {
this->name = name;
}
string getName() const {
return name;
}
void setDescription(const string description) {
this->description = description;
}
string getDescription() const {
return description;
}
void setManual(const string manual) {
this->manual = manual;
}
string getManual() const {
return manual;
}
void setPrice(const double price) {
this->price = price;
}
double getPrice() const {
return price;
}
void setIsNew(const bool is_new) {
this->is_new = is_new;
}
void setTimeToReplace(const int time_to_replace) {
this->time_to_replace = time_to_replace;
}
int getTimeToReplace() const {
return time_to_replace;
}
private:
string id;
string name;
string description;
string manual;
double price;
bool is_new;
int time_to_replace;
Vehicle* vehicle;
};
class AvailableSparePart : public SparePart {
public:
AvailableSparePart(string id, string name, Vehicle* v, int price, int time_to_replace,
int quantity, string location, bool is_new = true, string description = "", string manual = "")
: SparePart(id, name, v, price, time_to_replace, is_new, description, manual),
quantity(quantity),
location(location) {}
double price() {
return replacementPrice();
}
int time() {
return getTimeToReplace();
}
void output() {
cout << "Available Spare Part" << endl;
SparePart::output();
cout << " time: " << time() << endl;
cout << " price: " << price() << endl;
}
void setQuantity(const int quantity) {
this->quantity = quantity;
}
int getQuantity() const {
return quantity;
}
void setLocation(const string location) {
this->location = location;
}
string getLocation() const {
return location;
}
private:
int quantity;
string location;
};
class ContractedSparePart : public SparePart {
public:
ContractedSparePart(string id, string name, Vehicle* v, int price, int time_to_replace,
int delivery_time, double delivery_price, Vendor* vendor, bool is_new = true,
string description = "", string manual = "")
: SparePart(id, name, v, price, time_to_replace, is_new, description, manual),
delivery_time(delivery_time),
delivery_price(delivery_price),
vendor(vendor) {}
double price() {
return replacementPrice();
}
int time() {
return getTimeToReplace() + delivery_time;
}
void output() {
cout << "Contracted Spare Part" << endl;
SparePart::output();
cout << " time: " << time() << endl;
cout << " price: " << price() << endl;
}
void setDeliveryTime(const int delivery_time) {
this->delivery_time = delivery_time;
}
int getDeliveryTime() const {
return delivery_time;
}
void setDeliveryPrive(const double delivery_price) {
this->delivery_price = delivery_price;
}
double getDeliveryPrice() const {
return delivery_price;
}
private:
Vendor* vendor;
int delivery_time;
double delivery_price;
};
enum class Action {
ADD_VEHICLE,
ADD_VENDOR,
ADD_PART,
ADD_PART_QUANTITY,
LIST_PARTS,
CALCULATE_COST,
EXIT
};
Action menu() {
string prompt = "Choose an option:\n"
"1. Add a new vehicle\n"
"2. Add a new vendor\n"
"3. Add a new spare part\n"
"4. Add part quantity\n"
"5. List spare parts\n"
"6. Calculate the cost of replacement\n"
"7. Exit";
while (true) {
switch (AskFor<int>(prompt)) {
case 1:
return Action::ADD_VEHICLE; break;
case 2:
return Action::ADD_VENDOR; break;
case 3:
return Action::ADD_PART; break;
case 4:
return Action::ADD_PART_QUANTITY; break;
case 5:
return Action::LIST_PARTS; break;
case 6:
return Action::CALCULATE_COST; break;
case 7:
return Action::EXIT; break;
default:
cout << "Please enter a number between 1 and 6" << endl;
}
}
}
struct PartAndNumber {
PartAndNumber(SparePart* part, int number)
: part(part), number(number) {}
SparePart* part;
int number;
};
void add_vehicle(vector<Vehicle*>& vehicles);
void add_vendor(vector < Vendor*>& vendors);
void add_part(vector<PartAndNumber*>& parts, const vector<Vehicle*>& vehicles, const vector<Vendor*>& vendors);
void add_available_part(vector<PartAndNumber*>& parts, Vehicle* vehicle);
void add_contracted_part(vector<PartAndNumber*>& parts, Vehicle* vehicle, const vector<Vendor*>& vendors);
void add_part_number(vector<PartAndNumber*>& parts);
void list_parts(const vector<PartAndNumber*>& parts);
void calculate_cost(const vector<PartAndNumber*>& parts);
int main() {
vector<Vehicle*> vehicles;
vector<PartAndNumber*> parts;
vector<Vendor*> vendors;
while (true) {
Action action = menu();
switch (action) {
case Action::ADD_VEHICLE:
add_vehicle(vehicles);
break;
case Action::ADD_VENDOR:
add_vendor(vendors);
break;
case Action::ADD_PART:
add_part(parts,vehicles,vendors);
break;
case Action::ADD_PART_QUANTITY:
add_part_number(parts);
break;
case Action::LIST_PARTS:
list_parts(parts);
break;
case Action::CALCULATE_COST:
calculate_cost(parts);
break;
case Action::EXIT:
return 0;
}
}
}
void add_vehicle(vector<Vehicle*>& vehicles) {
string producer;
while (true) {
producer = AskFor<string>("New vehicle (producer): ");
if (Vehicle::isProducerValid(producer)) {
break;
}
cout << "Producer name is invalid. Try again." << endl;
}
string model = AskFor<string>("New vehicle (model):");
int year;
while (true) {
year = AskFor<int>("New vehicle (year):");
if (Vehicle::isYearValid(year)) {
break;
}
cout << "Year is invalid. Try again." << endl;
}
vehicles.push_back(new Vehicle(producer, model, year));
cout << "**************************************" << endl;
cout << "The vehicle was added to the database" << endl;
cout << "**************************************" << endl;
}
void add_vendor(vector <Vendor*>& vendors) {
string v_name = AskFor<string>("New vendor (name): ");
string address = AskFor<string>("New vendor (address): ");
string phone;
while (true) {
phone = AskFor<string>("New vendor (phone):");
if (Vendor::isPhoneNumber(phone)) {
break;
}
else cout << "Phone is invalid. Try again." << endl;
}
vector<string> delivery;
string del;
do {
cout << "New vendor(delivery) or q to stop: ";
if (del != "") {
delivery.push_back(del);
}
} while ((cin >> del) && del != "q");
vendors.push_back(new Vendor(v_name, address, phone, delivery));
cout << "**************************************" << endl;
cout << "The vendor was added to the database" << endl;
cout << "**************************************" << endl;
}
void add_part(vector<PartAndNumber*>& parts, const vector<Vehicle*>& vehicles, const vector<Vendor*>& vendors) {
string prompt = "Choose the type of spare part : Available(1) or Contracted(2); or q to exit : ";
do {
string model = AskFor<string>("Vehicle model: ");
Vehicle* vehicle = nullptr;
for (auto v : vehicles) {
if (v->getModel() == model) {
vehicle = v;
break;
}
}
if (vehicle == nullptr) {
cout << "Could not find a vehicle with this model." << endl;
return;
}
switch (AskFor<char>(prompt)) {
case '1':
add_available_part(parts, vehicle);
return;
break;
case '2':
add_contracted_part(parts, vehicle, vendors);
return;
break;
case 'q':
return;
break;
default:
cout << "No such option!";
}
} while (true);
}
void add_available_part(vector<PartAndNumber*>& parts, Vehicle* vehicle) {
string id = AskFor<string>("New spare part(id): ");
for (auto p : parts) {
if (p->part->getId() == id) {
cout << "Already available" << endl;
return;
}
}
string name = AskFor<string>("New spare part(name): ");
int price = AskFor<int>("New spare part(price): ");
int time_to_replace = AskFor<int>("New spare part(time to replace): ");
bool is_new = AskFor<bool>("New spare part(1 for new, 0 for recycled): ");
string description = AskFor<string>("New spare part(description): ");
string manual = AskFor<string>("New spare part(manual): ");
int quantity = AskFor<int>("New spare part(quantity): ");
string location = AskFor<string>("New spare part(location): ");
auto part = new AvailableSparePart(id, name, vehicle, price, time_to_replace, quantity, location, is_new, description, manual);
parts.push_back(new PartAndNumber(part, 0));
cout << "**************************************" << endl;
cout << "The spare part was added to the database" << endl;
cout << "**************************************" << endl;
}
void add_contracted_part(vector<PartAndNumber*>& parts, Vehicle* vehicle, const vector<Vendor*>& vendors) {
string id = AskFor<string>("New spare part(id): ");
for (auto p : parts) {
if (p->part->getId() == id) {
cout << "Already available" << endl;
return;
}
}
string v_name = AskFor<string>("New spare part(vendor name): ");
Vendor* vendor = nullptr;
for (auto v : vendors) {
if (v->getVendorName() == v_name) {
vendor = v;
break;
}
}
if (vendor == nullptr) {
cout << "Could not find a vendor with this name." << endl;
return;
}
string name = AskFor<string>("New spare part(name): ");
int price = AskFor<int>("New spare part(price): ");
int time_to_replace = AskFor<int>("New spare part(time to replace): ");
bool is_new = AskFor<bool>("New spare part(1 for new, 0 for recycled): ");
string description = AskFor<string>("New spare part(description): ");
string manual = AskFor<string>("New spare part(manual): ");
int delivery_time = AskFor<int>("New spare part(delivery time): ");
double delivery_price = AskFor<double>("New spare part(delivery price): ");
auto part = new ContractedSparePart(id, name, vehicle, price, time_to_replace, delivery_time, delivery_price, vendor, is_new, description, manual);
parts.push_back(new PartAndNumber(part, 0));
cout << "**************************************" << endl;
cout << "The spare part was added to the database" << endl;
cout << "**************************************" << endl;
}
void add_part_number(vector<PartAndNumber*>& parts) {
string id = AskFor<string>("Spare part (id): ");
for (auto p : parts) {
if (p->part->getId() == id) {
int parts_number = AskFor<int>("Number of parts: ");
p->number = parts_number;
cout << "***************************************************" << endl;
cout << "The number of spare parts was added to the database" << endl;
cout << "***************************************************" << endl;
return;
}
}
cout << "A spare part with this ID is not available.";
}
void list_parts(const vector<PartAndNumber*>& parts) {
double total_price = 0;
for (auto p : parts) {
p->part->output();
cout << endl;
double total_current_price = p->part->replacementPrice() * p->part->getTimeToReplace();
total_price = +total_current_price;
}
quicksort(parts, , parts.back);
cout << "The total price is" << total_price << endl;
}
void calculate_cost(const vector<PartAndNumber*>& parts) {
string id = AskFor<string>("Spare part(id): ");
for (auto p : parts) {
if (p->part->getId() == id) {
cout << "The cost for replacement is $" << p->part->replacementPrice() << endl;
return;
}
}
cout << "A spare part with this ID is not available.";
}
SparePart::~SparePart() {}
template <class Comparable>
void quicksort(vector<Comparable>& a)
{
quicksort(a, 0, a.size() - 1);
}
template <class Comparable>
void quicksort(vector<Comparable>& a, double low, double high)
{
if (low + 10 > high) {
insertionSort(a);
}
else {
double middle = (low + high) / 2;
if (a[middle] < a[low]) swap(a[low], a[middle]);
if (a[high] < a[low]) swap(a[low], a[high]);
if (a[high] < a[middle]) swap(a[middle], a[high]);
Comparable pivot = a[middle];
swap(a[middle], a[high - 1]);
int i, j;
for (i = low, j = high - 1; ;) {
while (a[++i] < pivot) {}
while (pivot < a[--j]) {}
if (i < j) swap(a[i], a[j]);
else break;
}
swap(a[i], a[high - 1]);
quicksort(a, low, i - 1);
quicksort(a, i + 1, high);
}
}
Thank you for the help!
Elements of Your vector are pointers! The easiest way is to add to class PartAndNumber
operator<(const PartAndNumber *other)
{
return this->part->id - other->part->id;
}

C++ Depth First Search of Trie with prefix parameter

I'm trying to implement a trie that can print out the frequency of words with a given prefix.
Edit: Thanks to #kaidul-islam finding my error with the following error:
new_word->child[letter]->prefixes_++;
Below is the fixed code:
Trie Class:
class Trie
{
public:
Trie(): prefixes_(0), is_leaf_(false), frequency_(0)
{
for (int i=0; i<26; i++)
{
child[i] = nullptr;
}
}
virtual ~Trie();
//Child nodes of characters from a-z
Trie *child[26];
//vector<Trie> child;
int prefixes_;
//accessor & mutator functions
bool GetIsLeaf() { return is_leaf_; }
void SetIsLeaf(bool val) { is_leaf_ = val; }
int GetFrequency() { return frequency_; }
void SetFrequency(int val) { frequency_ = val; }
int GetPrefixes() { return prefixes_; }
void SetPrefixes(int val) { prefixes_ = val; }
bool is_leaf_;
private:
//bool is_leaf_;
int frequency_;
};
Function in Question:
void AddWord(string &word, Trie *root)
{
Trie *new_word = root;
new_word->prefixes_++;
for(unsigned int i = 0 ; i < word.length(); i++)
{
int letter = (int)word[i] - (int)'a'; //extract character of word
if(new_word->child[letter] == nullptr)
{
new_word->child[letter] = new Trie;
}
/*cout << "not value of x: " << new_word->child[letter]->GetPrefixes() << endl;
int x = (new_word->child[letter]->GetPrefixes())+1;
cout << "value of x: " << x << endl;
new_word->child[letter]->SetPrefixes(x);*/
new_word->child[letter]->prefixes_++;
new_word = new_word->child[letter];
}
new_word->SetFrequency(new_word->GetFrequency()+1);
/*
cout << "Word: " << word << endl;
cout << "frequency: " << new_word->GetFrequency() << endl;
cout << "prefixes: " << new_word->GetPrefixes() << endl;
cout << "is leaf: " << new_word->GetIsLeaf() << endl << endl;
*/
}
After a quick inspection, I found you didn't initialize member variables in your constructor.
Trie(): prefixes_(0),
is_leaf_(false),
frequency_(0) {
for(int i = 0; i < 26; i++) {
child[i] = nullptr;
}
}
Unlike global variable, there is no guarantee that prefixes_ will be 0 by default on declaration. And child[i] is not guaranteed to be nullptr too. You need to initialize everything.

Object Hierarchy employee program - dereferencing pointer for cout

I am new to c++ and am working on a project for class. I know I that some of my functions are not correct. I am trying to get to a point to where I can at least see the output to continue working on it. I have included a brief description of that I am trying to do.
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class Employee
{
protected:
char* name[50];
public:
Employee()
{
}
Employee(char* name)
{
strcpy(name, name);
}
char* getName()
{
return *name;
}
void setName(char* name)
{
name = name;
}
/*virtual ~Employee()
{
delete[] name;
}*/
virtual void print() = 0;
};
class HourlyEmployee : public Employee
{
private:
float HourlySalary;
public:
HourlyEmployee()
{
HourlySalary = 0;
}
HourlyEmployee(char* name, float HourlySalary)
{
name = name;
HourlySalary = HourlySalary;
}
double getHourlySalary()
{
return HourlySalary;
//cout << "What is your Hourly Salary" << endl;
//cin >> HourlySalary;
}
void setHourlySalary(double HourlySalary)
{
}
void print()
{
cout << "Hourly Employee Name: " << &name << endl
<< "Salary: " << &HourlySalary << "per hour" << endl;
}
};
class SalariedEmployee : public Employee
{
private:
float MonthlySalary;
public:
SalariedEmployee()
{
MonthlySalary = 0;
}
SalariedEmployee(char* name, float MonthlySalary)
{
}
double getMonthlyySalary()
{
return MonthlySalary;
//cout << "What is your Hourly Salary" << endl;
//cin >> MonthlySalary;
}
void setMonthlySalary(double MonthlySalary)
{
}
void print()
{
cout << "Hourly Employee Name: " << name << endl
<< "Salary: " << MonthlySalary << "per month" << endl;
}
};
int main() {
SalariedEmployee* S = new SalariedEmployee();
SalariedEmployee S1("Joe Bob", '4500');
HourlyEmployee* H = new HourlyEmployee();
HourlyEmployee H1("Jim Bob", '20');
S1.print();
H1.print();
delete S, H;
system("pause");
return 0;
}
From the description of your exercise I concluded that you're asking for something like this:
#include <iostream>
using namespace std;
class Employee
{
protected:
char name[50];
public:
Employee()
{
}
Employee(char* name)
{
strncpy_s(this->name, 49, name, 49);
}
char* getName()
{
return this->name;
}
void setName(char *name)
{
strncpy_s(this->name, 49, name, 49);
}
virtual void print() = 0;
};
class HourlyEmployee : public Employee
{
private:
float hourlySalary;
public:
HourlyEmployee()
{
hourlySalary = 0;
}
HourlyEmployee(char* name, float HourlySalary)
{
strncpy_s(this->name, 49, name, 49);
this->hourlySalary = HourlySalary;
}
double getHourlySalary()
{
return hourlySalary;
//cout << "What is your Hourly Salary" << endl;
//cin >> HourlySalary;
}
void setHourlySalary(double HourlySalary)
{
this->hourlySalary = HourlySalary;
}
void print()
{
cout << "Hourly Employee Name: " << this->name << endl
<< "Salary: " << hourlySalary << " per hour" << endl;
}
};
class SalariedEmployee : public Employee
{
private:
float MonthlySalary;
public:
SalariedEmployee()
{
MonthlySalary = 0;
}
SalariedEmployee(char* name, float MonthlySalary)
{
strncpy_s(this->name, 49, name, 49);
this->MonthlySalary = MonthlySalary;
}
double getMonthlyySalary()
{
return MonthlySalary;
//cout << "What is your Hourly Salary" << endl;
//cin >> MonthlySalary;
}
void setMonthlySalary(double MonthlySalary)
{
this->MonthlySalary = MonthlySalary;
}
void print()
{
cout << "Hourly Employee Name: " << name << endl
<< "Salary: " << MonthlySalary << " per month" << endl;
}
};
int main()
{
Employee * employee[2];
employee[0] = new SalariedEmployee("Joe Bob", 4000);
employee[1] = new HourlyEmployee("Jim Bob", 20);
for (int i = 0; i < 2; i++)
{
employee[i]->print();
}
for (size_t i = 0; i < 2; i++)
{
delete employee[i];
}
system("pause");
return 0;
}
First off,your name variable's gotta be of type char[50],not *char[50]. So I used strncpy(or the safe function strncpy_s) to copy the name in our constructor. Since you're dealing with chars,you cannot assign it like you did in some parts of your code,like this name = name. And I used this->name because the variable names are identical. Next off,in your main function you gotta have the Employee class and then assign it to an HourlyEmployee and SalariedEmployee , because those are the principles of polymorphism. Hope that I have helped you and if you have any questions,don't hesitate to ask.
`

C++ Program crashing from print function

At the moment my program is crashing after displaying one line out of the 250 it is supposed to display. Here is my code:
string MovieList::PrintAll() {
for (int i = 0; i < last_movie_index; i++) {
movies[last_movie_index].Movie::PrintMovie();
}
}
string Movie::PrintMovie() {
cout << fixed << setprecision(1) << rating << "\t\t" << votes << "\t\t" << "(" <<
year_made << ")" << "\t" << name << endl;
}
Full Movie and MovieList class:
class Movie {
public:
Movie();
Movie(string n, int y, int v, double r);
string get_name();
void set_name(string n);
int get_year();
void set_year(int y);
int get_votes();
void set_votes(int v);
double get_rating();
void set_rating(double r);
string PrintMovie();
private:
string name;
int year_made;
int votes;
double rating;
};
Movie::Movie() {
name = "null";
year_made = 0;
votes = 0;
rating = 0.0;
}
Movie::Movie(string n, int y, int v, double r) {
name = n;
year_made = y;
votes = v;
rating = r;
}
string Movie::get_name() {
return name;
}
void Movie::set_name(string n) {
name = n;
}
int Movie::get_year() {
return year_made;
}
void Movie::set_year(int y) {
year_made = y;
}
int Movie::get_votes() {
return votes;
}
void Movie::set_votes(int v) {
votes = v;
}
double Movie::get_rating() {
return rating;
}
void Movie::set_rating(double r) {
rating = r;
}
string Movie::PrintMovie() {
cout << fixed << setprecision(1) << rating << "\t\t" << votes << "\t\t" << "(" <<
year_made << ")" << "\t" << name << endl;
}
class MovieList {
public:
MovieList(int size);
~MovieList();
int Length();
bool IsFull();
void Add(Movie const& m);
string PrintAll();
private:
Movie* movies;
int last_movie_index;
int movies_size;
int movie_count = 0;
};
MovieList::MovieList(int size) {
movies_size = size;
movies = new Movie[movies_size];
last_movie_index = -1;
}
MovieList::~MovieList() {
delete [] movies;
}
int MovieList::Length() {
return last_movie_index;
}
bool MovieList::IsFull() {
return last_movie_index == movies_size;
}
void MovieList::Add(Movie const& m)
{
if (IsFull()) {
cout << "Cannot add movie, list is full" << endl;
return;
}
last_movie_index++;
movies[last_movie_index] = m;
}
string MovieList::PrintAll() {
for (int i = 0; i < last_movie_index; i++) {
movies[i].Movie::PrintMovie();
}
}
My array movies is dynamically allocated (i.e movies = new Movie[movies_size];). I noticed that using cout << movies[1] << endl will not work in the PrintAll function. Is this why it is crashing possibly? And what can I do to fix it?
This won't solve your problem, but if you want to make cout << movies[i] << endl work, then you need to define the following function in the Movie class:
friend ostream& operator<<(ostream& ostr, const Movie& movie){
ostr << fixed << setprecision(1) << rating << "\t\t" << votes << "\t\t" << "(" <<
year_made << ")" << "\t" << name ;
}