this its C++.
i dont really know wheres the problem since the both of the static cast are equally typed but it only display correctly employee info, when it comes to patient info it only display date in and date out, but no person info, (employee does correctly print person info)
void *print( ){
Node *aux;
aux = this->head;
while(aux){
Employee *employee = static_cast<Employee*>(aux->getPerson());
Patient *patient = static_cast<Patient*>(aux->getPerson());
if(employee) {
employee->info();
}
else if (patient){
patient->info();
//Should be one of the cases above
}
aux = aux->getNext();
}
return 0;
just at the moment i print this, it prints only employee info but patient info its not displayed.
class Patient: public Person {
private:
int Id_Patient;
Person person;
string Date_In;
string Date_Out;
public:
Patient(){
this->Date_In;
this->Date_Out;
}
Patient (int Id_Patient, Person person){
this->Id_Patient=Id_Patient;
this->person=person;
}
Patient (int Id_Patient, Person person, string Date_In, string Date_Out){
this->Id_Patient=Id_Patient;
this->Date_Out=Date_Out;
this->Date_In=Date_In;
}
void setId_Patient(int Id_Patient){
this->Id_Patient=Id_Patient;}
int getId_Patient(){
return this->Id_Patient;}
void setDate_In(string Date_In){
this->Date_In=Date_In;}
string getDate_In(){
return this->Date_In;}
void setDate_Out(string Date_Out){
this->Date_Out=Date_Out;}
string getDate_Out(){
return this->Date_Out;}
void setPerson(Person person) {
this->person=person; }
Person getPerson() {
return this->person;}
void info() {
cout <<"=================================" << endl;
cout << "Patient ID: " << this->Id_Patient << endl;
this->person.info();
cout << "Date_In: " << this->Date_In << endl;
cout << "Date_Out: "<< this->Date_Out << endl;
cout <<"=================================" << endl;
}
}; //clase patient
class Employee: public Person {
private:
int Employee_Code;
Person person;
double Salary;
public:
Employee() {
this->Employee_Code;
this->Salary;}
Employee(int Employee_Code, Person person){
this->Employee_Code=Employee_Code;
this->person=person;
}
Employee(int Employee_Code, double Salary){
this->Employee_Code=Employee_Code;
this->Salary=Salary;
}
Employee(int Employee_Code, Person person, double Salary){
this->Employee_Code=Employee_Code;
this->person=person;
this->Salary=Salary;
}
void setEmployee_Code(int Employee_Code){
this->Employee_Code=Employee_Code;}
int getEmployee_Code(){
return this->Employee_Code;}
void setSalary(double Salary){
this->Salary=Salary;}
double getSalary(){
return this->Salary;}
void setPerson(Person person) {
this->person=person; }
Person getPerson() {
return this->person;}
void info() {
cout <<"=================================" << endl;
cout << "Employee_Code: " << this->Employee_Code << endl;
this->person.info();
cout << "Salary: " << this->Salary << endl;
cout <<"=================================" << endl;
}
}; //clase employee
It appears that OP has confused static_cast with dynamic_cast. But there is a much better way to do this that eliminates the need for any casting: add pure virtual method virtual void info()=0; to Person.
Patient and Employee's info will implement Person's info and print can simply
aux->getPerson()->info();
All done.
off topic, what point is there to returning void * from print? void * is a failure of imagination, bad planning, or an interface with a C library in C++. You should almost never use it, and certainly not to return 0.
Related
#include <iostream>
using namespace std;
class Student
{
protected:
long studentID;
public:
void setStudentID(long s_){ studentID = s_; }
Student(): studentID(0){}
long get_StudentID(){ return studentID; }
};
class Exam : public Student
{
protected:
float mark;
public:
void setMark(float m_){ mark = m_; }
Exam(): mark(0){}
float getMark(){ return mark; }
};
class Sports : public Student
{
protected:
float score;
public:
void setScore(float s_){ score = s_; }
Sports(): score(0){}
float getScore(){ return score; }
};
class Result: public Student, public Exam, public Sports
{
private:
float Total;
public:
float getTotal(){ return getMark() * getScore(); }
void display();
};
void Result::display()
{
cout << "Student ID = " << get_StudentID() << endl;
cout << "Exam Mark = " << getMark() << endl;
cout << "Sports Score = " << getScore() << endl;
cout << "Total Mark = " << getTotal();
}
int main()
{
Result st1;
st1.display();
return 0;
}
I wrote this code in Code::Blocks and it's incomplete yet , but this error that says "refrence to get_StudentID is ambigous" confused me; What's wrong with it?
Should I delete using namespace and insert std:: before all (cout, cin & endl) statments?
You are misunderstanding inheritance. For example, the class Exam with this line
class Exam : public virtual Student
is publicly inheriting from Student. Public inheritance should only be used in an IS-A relationship. In this case, Exam is not a Student so you shouldn't use public inheritance. Same goes for Sports.
"Call is ambiguous" means that when you call get_StudentID from Result the compiler can't decide between Exam::get_StudentID or Sports::get_StudentID which they both inherit from Student.
Instead:
Remove the inheritance, don't use inheritance anywhere here. I would completely remake this and make a Student class with Exam and Sports member objects (which can become vector of objects later if needed) and call the needed functions from the member objects instead. As a general tip, avoid multiple inheritance unless completely necessary.
This is an easy fix
remove Student from Results base class
make Student public virtual from both Exam and Sports class
#include <iostream>
using namespace std;
class Student
{
protected:
long studentID;
public:
void setStudentID(long s_){ studentID = s_; }
Student(): studentID(0){}
long get_StudentID(){ return studentID; }
};
class Exam : public virtual Student
{
protected:
float mark;
public:
void setMark(float m_){ mark = m_; }
Exam(): mark(0){}
float getMark(){ return mark; }
};
class Sports : public virtual Student
{
protected:
float score;
public:
void setScore(float s_){ score = s_; }
Sports(): score(0){}
float getScore(){ return score; }
};
class Result: public Exam, public Sports
{
private:
float Total;
public:
float getTotal(){ return getMark() * getScore(); }
void display();
};
void Result::display()
{
cout << "Student ID = " << get_StudentID() << endl;
cout << "Exam Mark = " << getMark() << endl;
cout << "Sports Score = " << getScore() << endl;
cout << "Total Mark = " << getTotal();
}
int main()
{
Result st1;
st1.display();
return 0;
}
Godbolt: https://godbolt.org/z/4f5n8M5of
I'm having a problem understanding vectors of pointers to class objects, I tried a test code to try and understand it but whenever I enter a name and try to output it, it prints out numbers instead of the actual name that I entered. I'm hoping someone can explain this to me as I'm new to these concepts.
Also
Pets[0]->print(); dosent print at all while:
cout << "in main: " << Pets[0] << endl;
prints.
class Pet
{
public:
string name;
Pet(const string&);
string getName() const
{
return name;
}
void setName(const string& Name)
{
name = Name;
}
void print()const;
}
int main()
{
vector<Pet*> Pets;
string names;
int done = NULL;
do
{
{
cout << "Name: ";
cin >> names;
Pets.push_back(new Pet(names));
cin.ignore();
}
cout << "Add another ?" << endl;
cin >> done;
} while (done != 0);
Pets[0]->print();
cout << "in main: " << Pets[0] << endl;
system("pause");
}
Pet::Pet(const string& Name)
{
}
void Pet::print()const
{
cout << "Name: " << name;
}
The constructor of Pet does not assign the parameter, hence it remains empty.
Write...
Pet::Pet(const string& Name) : name(Name) { }
to do this initialization.
I am confused as to why casting a derived class to a pointer of base class calls upon the derived class method when I haven't used the virtual keyword. Is this normal behavior? Doesn't the pointer hold a Person object in memory, therefore casting it to a Student should not have any affect to its contents?
class Person {
public:
Person()
{
cout << "Creating Person Class" << endl;
}
void about_me()
{
cout << "I am a person" << endl;
}
};
class Student : protected Person {
public:
Student()
{
cout << "Creating Student Class" << endl;
}
void about_me()
{
cout << " I am a student " << endl;
}
};
int main()
{
Person* pperson = new Person();
Student* pstudent = new Student();
pperson->about_me();
pstudent->about_me();
pperson-> about_me();
((Student*)pperson)-> about_me(); // this is the line where I do the cast
return 0;
}
The output of the code is the following
Creating Person Class
Creating Person Class
Creating Student Class
I am a person
I am a student
I am a person
I am a student
Your code "works" because neither of your about_me() methods access their respective this pointers for anything.
Technically speaking, what you are doing is undefined behavior, because pperson does not point at a valid Student object, but you are telling the compiler to treat it as if it were. So literally anything can happen.
In many common compiler implementations, a class method call like pperson->about_me() is actually calling more like about_me(pperson), where about_me() gets implemented as a standalone function with a this input parameter. So code you have shown might be implementation by the compiler more like this under the hood (not exactly, but you should get the idea):
struct Person
{
};
void Person_Person(Person *this)
{
cout << "Creating Person Class" << endl;
}
void Person_about_me(Person *this)
{
cout << "I am a person" << endl;
}
struct Student
{
};
void Student_Student(Student *this)
{
Person_Person(this);
cout << "Creating Student Class" << endl;
}
void Student_about_me(Student *this)
{
cout << " I am a student " << endl;
}
int main()
{
//Person* pperson = new Person();
byte *buf1 = new byte[sizeof(Person)];
Person* pperson = (Person*) buf1;
Person_Person(pperson);
//Student* pstudent = new Student();
byte *buf2 = new byte[sizeof(Student)];
Student* pstudent = (Student*) buf2;
Student_Student(pstudent);
//pperson->about_me();
Person_about_me(pperson);
//pstudent->about_me();
Student_about_me(pstudent);
//pperson-> about_me();
Person_about_me(pperson);
//((Student*)pperson)-> about_me();
Student_about_me((Student*)pperson);
return 0;
}
So, in the 4th call to about_me(), you are instructing the compiler to call Student::about_me() instead of letting it call Person::about_me() normally, with its this parameter set to a Person* pointer that is type-casted to Student*. Since this is not dereferenced by about_me(), the call is "successful" in that you see the "expected" output. It doesn't matter what this points to in this case, because it is not being used.
Now, try adding some data members to your classes, and then output those members in about_me(), and you will see very different, very unexpected/random results, due to the undefined behavior you are invoking. For example:
class Person
{
protected:
string m_name;
public:
Person(const string &name)
: m_name(name)
{
cout << "Creating Person Class" << endl;
}
void about_me()
{
cout << "I am a person, my name is " << m_name << endl;
}
};
class Student : protected Person
{
private:
int m_id;
string m_school;
public:
Student(const string &name, int id, const string &school)
: Person(name), m_id(id), m_school(school)
{
cout << "Creating Student Class" << endl;
}
void about_me()
{
cout << "I am a student, my name is " << m_name << ", my id is " << m_id << " at " << m_school << endl;
}
};
int main()
{
Person* pperson = new Person("John Doe");
Student* pstudent = new Student("Jane Doe", 12345, "Some School");
pperson->about_me(); // "I am a person, my name is John Doe"
pstudent->about_me(); // "I am a student, my name is Jane Doe, my id is 12345 at Some School"
pperson->about_me(); // "I am a person, my name is John Doe"
((Student*)pperson)->about_me(); // runtime error!
delete pstudent;
delete pperson;
return 0;
}
Live Demo
I am relatively new to classes and was introduced to copy constructors and overloading last week. I am supposed to overload the = operator and use it to assign multiple variables using the class name.
For some reason, running the program causes a popup saying
program.cpp has stopped responding.
I am positive there are minor/major things that I am missing due to me being a rookie with objects in C++.
Any advice is very much appreciated!
#include<iostream>
#include<string>
using namespace std;
class Employee
{
private:
char *name;
string ID;
double salary;
public:
Employee() {}
Employee(char *name, string eid, double salary) {}
Employee(const Employee &obj)
{
name = new char;
ID = obj.ID;
salary = obj.salary;
}
~Employee() {}
void setName(char *n)
{
name = n;
}
void setID(string i)
{
ID = i;
}
void setSalary(double s)
{
salary = s;
}
char getName()
{
return *name;
}
string getID()
{
return ID;
}
double getSalary()
{
return salary;
}
Employee operator = (Employee &right)
{
delete[] name;
ID = right.ID;
salary = right.salary;
return *this;
}
};
int main()
{
Employee e1("John", "e222", 60000), e2(e1), e3, e4;
e3 = e4 = e2;
e2.setName("Michael");
e2.setSalary(75000);
e3.setName("Aaron");
e3.setSalary(63000);
e4.setName("Peter");
cout << "\nName: " << e1.getName() << "\nID: " << e1.getID() << "\nSalary: " << e1.getSalary() << endl;
cout << "\nName: " << e2.getName() << "\nID: " << e2.getID() << "\nSalary: " << e2.getSalary() << endl;
cout << "\nName: " << e3.getName() << "\nID: " << e3.getID() << "\nSalary: " << e3.getSalary() << endl;
cout << "\nName: " << e4.getName() << "\nID: " << e4.getID() << "\nSalary: " << e4.getSalary() << endl;
return 0;
}
There are several issues with this code.
The first issue is in the constructor Employee(char *name, string eid, double salary) {} which is just doing nothing and ignoring the passed data whereas it should be using it to initialize the fields (class member data).
Employee(char *name, string eid, double salary)
{
const size_t bufferSize = strlen(name) + 1;
this->name = new char[bufferSize];
memcpy(this->name, name, bufferSize);
this->ID = eid;
this->salary = salary;
}
The second issue is in the copy constructor Employee(const Employee &obj) , where you are just initializing the name (with single byte of char) and that's it. What the copy constructor suppose to do is initialize the fields (class members) of the class with the fields of the class object being passed to it.
Employee(const Employee &obj)
{
const size_t bufferSize = strlen(name) + 1;
this->name = new char[bufferSize];
memcpy(this->name, name, bufferSize);
ID = obj.ID;
salary = obj.salary;
}
the third issue is with the default constructor which is suppose to initialize the name pointer with the NULL so that the destructor could clean it up nicely:
Employee() : name(NULL) {}
~Employee()
{
if (NULL != name)
delete[] name;
}
the fourth and last problem is with the assignment operator that's suppose to properly initialize the name member data instead of deleting it (which doesn't make sense)
Employee operator = (Employee &right)
{
if (NULL != this->name)
delete[] this->name;
const size_t bufferSize = strlen(right.name) + 1;
this->name = new char[bufferSize];
memcpy(this->name, right.name, bufferSize);
ID = right.ID;
salary = right.salary;
return *this;
}
The problem is this line:
delete[] name;
You shouldn't delete anything you haven't allocated with new first. If you delete the above line, your program kind of works. :)
Here's a slightly revised version of your program that works:
#include<iostream>
#include<string>
using namespace std;
class Employee
{
private:
char *name;
string ID;
double salary;
public:
Employee() {}
Employee(char *name, string eid, double salary)
: name (name) // ADDED THESE
, ID(eid)
, salary(salary)
{
}
Employee(const Employee &obj)
{
name = obj.name; // WAS: new char;
ID = obj.ID;
salary = obj.salary;
}
~Employee() {}
void setName(char *n)
{
name = n;
}
void setID(string i)
{
ID = i;
}
void setSalary(double s)
{
salary = s;
}
char * getName()
{
return name;
}
string getID()
{
return ID;
}
double getSalary()
{
return salary;
}
Employee operator = (const Employee &right)
{
name = right.name; // WAS: delete[] name;
ID = right.ID;
salary = right.salary;
return *this;
}
};
int main()
{
Employee e1("John", "e222", 60000), e2(e1), e3, e4;
e3 = e4 = e2;
e2.setName("Michael");
e2.setSalary(75000);
e3.setName("Aaron");
e3.setSalary(63000);
e4.setName("Peter");
cout << "\nName: " << e1.getName() << "\nID: " << e1.getID() << "\nSalary: " << e1.getSalary() << endl;
cout << "\nName: " << e2.getName() << "\nID: " << e2.getID() << "\nSalary: " << e2.getSalary() << endl;
cout << "\nName: " << e3.getName() << "\nID: " << e3.getID() << "\nSalary: " << e3.getSalary() << endl;
cout << "\nName: " << e4.getName() << "\nID: " << e4.getID() << "\nSalary: " << e4.getSalary() << endl;
return 0;
}
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.
`