C++ Constructor Initilizer - c++

I am trying to use constructor initializer for name and time but the visual studio is giving me errors, I do not see any issues with it, it seems fine to me, I tried to see the problem, I tried other things as well, Please Help. Thanks you in advance.
Any help really appreciated, I added all the header file and implementation of Entry class, I know it seems, I added so you can see it.
// Entry.h
#pragma once
#include <iostream>
#include <string>
#include "RelationType.h"
using namespace std;
class Name
{
public:
Name();
Name(string firstName, string middleName, string lastName);
string GetFristName() const;
string GetLastName() const;
string GetMiddleName() const;
char GetMiddleInitial() const;
RelationType ComparedTo(Name otherName) const;
private:
string first;
string last;
string middle;
};
//Entry.cpp
#include "Entry.h"
#include<iostream>
#include <string>
using namespace std;
Entry::Entry() {}
Entry::Entry(string firstName, string middleName, string lastName,
int initHours, int initMinutes, int initSeconds)
: name{ (firstName, middleName, lastName) , //name is where its mad at
time(initHours, initMinutes, initSeconds) } {}
string Entry::GetNameStr () const
{
return (name.GetFirstName() + ' ' + name.GetLastName());
}
string Entry::GetTimeStr () const
{
return (name.FirstName() + ' ' + name.LastName());
}
// Name.h
#pragma once
#include <iostream>
#include <string>
#include "RelationType.h"
using namespace std;
class Name
{
public:
Name();
Name(string firstName, string middleName, string lastName);
string GetFristName() const;
string GetLastName() const;
string GetMiddleName() const;
char GetMiddleInitial() const;
RelationType ComparedTo(Name otherName) const;
private:
string first;
string last;
string middle;
};
// RealtionType.h
#pragma once
#ifndef RELATION
#define RELATION
enum RelationType { BEFORE, SAME, AFTER };
#endif
// TimeOfDay.h
#pragma once
class TimeOfDay
{
public:
//Intentionally missed const, see what happened without const
TimeOfDay(); // zero timepfday object
TimeOfDay(int hours, int minutes, int seconds); //takes 3 parameters
TimeOfDay Increment() const; //increment by 1 sec
void Write() const; //write the timeofday obj to print
bool Equal(TimeOfDay otherTime) const; //true if timeofday obj equals othertime
bool LessThan(TimeOfDay otherTime) const; //const, true if the timeofday obj is
//before itherTime
private:
int hours;
int minutes;
int seconds;
};

Your Entry class constructor code should be something like below
Entry::Entry(string firstName, string middleName, string lastName,
int initHours, int initMinutes, int initSeconds)
: name(firstName, middleName, lastName)
, time(initHours, initMinutes, initSeconds) {}

Related

Why am I getting an undefined reference to a constructor despite not calling it?

This error is beyond my current understanding. I have tried for hours to figure out why this is the case. Can someone help me?
Warrior.h
#include <string>
#ifndef __WARRIOR_H__
#define __WARRIOR_H__
#include "Character.h"
// HeroType type;
// string name;
// double health;
// double attackStrength;
class Warrior : public Character {
private:
string allegiance;
public:
Warrior(const string & _name, double _health, double _attackStrength, string _allegiance) : Character(WARRIOR, _name, _health, _attackStrength), allegiance(_allegiance){}
void attack(Character &);
};
#endif
// Warrior::Warrior(const string & _name, double _health, double _attackStrength, string _allegiance) : Character(WARRIOR, _name, _health, _attackStrength), allegiance(_allegiance)
// {}
Warrior.cpp
#include <iostream>
#include <vector>
#include <cstdlib>
#include "Warrior.h"
using namespace std;
void Warrior::attack(Character &opponent) {
Warrior &opp = dynamic_cast<Warrior &>(opponent);
if (opp.allegiance != allegiance)
{
double totalDamage;
totalDamage = (health / MAX_HEALTH);
opp.damage(totalDamage);
}
}
// Lecturer::Lecturer(const string & name,
// const string & addr,
// const string & email,
// const string & eid,
// double courseRate,
// double emplPerc)
// : Employee(name, addr, email, eid), courseRate(courseRate), emplPerc(emplPerc)
// {}
Character.h
#include <string>
using namespace std;
#ifndef __CHARACTER_H__
#define __CHARACTER_H__
enum HeroType {WARRIOR, ELF, WIZARD};
const double MAX_HEALTH = 100.0;
class Character {
protected:
HeroType type;
string name;
double health;
double attackStrength;
public:
Character(HeroType type, const string &name, double health, double attackStrength);
HeroType getType() const;
const string & getName() const;
int getHealth() const;
void damage(double d);
bool isAlive() const;
virtual void attack(Character &) = 0; //Abstract
};
#endif
Character.cpp
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
#include "Character.h"
Character::Character(HeroType type, const string &name, double health, double attackStrength) {
this->type = type;
this->name = name;
this->health = health;
this->attackStrength = attackStrength;
}
HeroType Character::getType() const {
return type;
}
const string & Character::getName() const {
return name;
}
int Character::getHealth() const {
return health;
}
void Character::damage(double d) {
health = health - d;
}
bool Character::isAlive() const {
return (health > 0);
}
Compiler error
In function Warrior::Warrior(std::string const&, double, double, std::string):
main.cpp:(.text._ZN7WarriorC2ERKSsddSs[_ZN7WarriorC5ERKSsddSs]+0x46): undefined reference to Character::Character(HeroType, std::string const&, double, double)
Warrior.o: In function Warrior::attack(Character&):
Warrior.cpp:(.text+0x87): undefined reference to Character::damage(double)
collect2: error: ld returned 1 exit status
Why am I getting an undefined reference to a constructor despite not calling it?
But you are calling it.
Warrior(const string & _name, double _health, double _attackStrength, string _allegiance) : Character(WARRIOR, _name, _health, _attackStrength), allegiance(_allegiance){}
calls the constructor referenced in the error message, namely:
Character::Character(HeroType type, const string &name, double health, double attackStrength)
As Jeremy says, it looks like you are failing to include Character.cpp in your build, hence the 'undefined reference' errors.

Error with Class in C++ for my project

I am new to this. Basically I just learnt how to use class in C++. When I try to print out, the values just seem to be 0. Can anyone help me out? Its supposed to print out:
Susan Myers 47899 Accounting Vice President
Mark Jones 39119 IT Position
Joy Rogers 81774 Manufacturing Engineer
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee
{
private:
string name;
int idNumber;
string department;
string position;
public:
Employee()
{
name=" ";
idNumber=0;
department=" ";
position=" ";
}
Employee(string, int, string, string)
{
int id;
string n,d,p;
name=n;
idNumber=id;
department=d;
position=p;
}
Employee(string, int)
{
string n;
int id;
name=n;
idNumber=id;
}
void setName(string)
{
string n;
name=n;
}
void setId(int)
{
int id;
idNumber=id;
}
void setDepartment(string)
{
string d;
department=d;
}
void setPosition(string)
{
string p;
position=p;
}
string getName() const
{
return name;
}
int getId() const
{
return idNumber;
}
string getDepartment() const
{
return department;
}
string getPosition() const
{
return position;
}
};
int main()
{
Employee e1;
Employee e2;
Employee e3;
e1.setName("Susan Meyers");
e2.setName("Mark Jones");
e3.setName("Joy Rogers");
e1.setId(47899);
e2.setId(39119);
e3.setId(81744);
e1.setDepartment("Accounting");
e2.setDepartment("IT");
e3.setDepartment("Manufacturing");
e1.setPosition("Vice President");
e2.setPosition("Programmer");
e3.setPosition("Engineer");
cout<<"---------------------------------------"<<endl;
cout<<"Name"<<setw(6)<<"ID Number"<<setw(10)<<"Department"<<setw(12)<<"Position"<<endl;
cout<<e1.getName()<<setw(6)<<e1.getId()<<setw(10)<<e1.getDepartment()<<setw(12)<<e1.getDepartment()<<endl;
cout<<e2.getName()<<setw(6)<<e2.getId()<<setw(10)<<e2.getDepartment()<<setw(12)<<e2.getDepartment()<<endl;
cout<<e3.getName()<<setw(6)<<e3.getId()<<setw(10)<<e3.getDepartment()<<setw(12)<<e3.getDepartment()<<endl;
return 0;
}
This is what you get when you rely on guesswork rather than properly reading an introductory textbook on C++
A constructor of the Employee class which (apart from a blank line that I've removed) you define as
Employee(string, int, string, string)
{
int id;
string n,d,p;
name=n;
idNumber=id;
department=d;
position=p;
}
has the following effects.
The four arguments passed by the caller are ignored, since they are not named.
Four default-initialised variables (id, n, d, and p) are defined local to the constructor body. id will be uninitialised. The others, since they are std::string, are default-initialised (to an empty string)
The next four statements copy those variables into class members. The result is that initialising idNumber has undefined behaviour (since id is uninitialised) and the three strings are initialised to empty strings.
To get the effect that (I assume) you intend, change this to;
Employee(std::string n, int id, std::string d, std::string p)
{
name=n;
idNumber=id;
department=d;
position=p;
}
Note that I'm calling string by its full name std::string. That allows removing the using namespace std which (among other things) is BAD practice in header files.
Even better, change this to
Employee(const std::string &n, int id, const std::string &d, const std::string &p) :
name(n), idNumber(id), department(d), position(p)
{
}
which passes the strings by const reference (avoids additional copies of std::strings) and uses an initialiser list instead of assigning to members in the constructor.
Similar comments apply to ALL of the member functions of Employee, except that only constructors can have initialiser lists.
Errors made
Presentation
Your code is extremely cluttered, and has much irrelevant stuff.
Syntax
void setPosition(string){
Here your function has no argument! What is string?
Code
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee{
public:
string name;
int idNumber;
string department;
string position;
void setName(string n){
name=n;
}
void setId(int k){
int id;
idNumber=id;
}
void setDepartment(string d){
department=d;
}
void setPosition(string p){
position=p;
}
string getName(){
return name;
}
int getId(){
return idNumber;
}
string getDepartment(){
return department;
}
string getPosition(){
return position;
}
};
int main(){
Employee e1;
Employee e2;
Employee e3;
e1.setName("Susan Meyers");
e2.setName("Mark Jones");
e3.setName("Joy Rogers");
e1.setId(47899);
e2.setId(39119);
e3.setId(81744);
e1.setDepartment("Accounting");
e2.setDepartment("IT");
e3.setDepartment("Manufacturing");
e1.setPosition("Vice President");
e2.setPosition("Programmer");
e3.setPosition("Engineer");
cout<<"---------------------------------------"<<endl;
cout<<"Name"<<" "<<"ID Number"<<" "<<"Department"<<" "<<"Position"<<endl;
cout<<e1.getName()<<" "<<e1.getId()<<" "<<e1.getDepartment()<<" "<<e1.getPosition()<<endl;
cout<<e2.getName()<<" "<<e2.getId()<<" "<<e2.getDepartment()<<" "<<e2.getPosition()<<endl;
cout<<e3.getName()<<" "<<e3.getId()<<" "<<e3.getDepartment()<<" "<<e3.getPosition()<<endl;
}
Output
---------------------------------------
Name ID Number Department Position
Susan Meyers 32767 Accounting Vice President
Mark Jones 32767 IT Programmer
Joy Rogers 32767 Manufacturing Engineer
Explanation
I have shortened your code by 50%(shows how much redundant stuff you had), and here is a working code.
void setDepartment(string d){
department=d;
}
Here, string d is defined IN the function as an argument. Note that your code also cout<< department twice, and I have corrected that for you in my above code.
Hope this helps.

Trouble with using parent constructors

I'm currently working on an assignment to expand on a program we previously made, involving the use of header files, and parent classes. In the original, I have 2 header files. Person.h, and OCCCDate.h. In the new one, I am creating one called OCCCPerson.h. It's an incredibly simple class that basically just uses Person, just with 1 added variable.
My problem is, I cant figure out how to use the parent constructor properly.
Here is the Person.h file.
#ifndef PERSON_H
#define PERSON_H
#include <string>
#include "OCCCDate.h"
using namespace std;
class Person{
private:
string firstName;
string lastName;
OCCCDate dob;
public:
Person();
Person(string, string);
Person(string, string, OCCCDate);
string getFirstName();
string getLastName();
void setFirstName(string);
void setLastName(string);
int getAgeInYears();
bool equals(Person);
string toString();
};
#endif
And here is my OCCCPerson.h file
#ifndef OCCCPERSON_H
#define OCCCPERSON_H
#include <string>
#include "OCCCDate.h"
#include "Perosn.h"
using namespace std;
class OCCCPerson : Person{
protected:
string studentID;
public:
OCCCPerson(string firstName, string lastName, OCCCDate dob, string studentID);
OCCCPerson(Person p, string studentID);
string getStudentID();
bool equals(OCCCPerson p);
string toString();
};
#endif;
I cant seem to call on the parents constructor to get things like the firstname, lastname, and dob(date of birth). From my handout, it says the parent constructor has to be initialized with, : Person(parameters), where parameters are things in the parent class. However, I have no idea where to put that. Sorry for writing so much. I just couldn't figure out how to shrink that down.
Oh, and here is OCCCDate.h just in case
#ifndef OCCCDATE_H
#define OCCCDATE_H
#include<string>
using namespace std;
class OCCCDate{
private:
bool OCCCDate_US;
bool OCCCDate_EURO;
int dayOfMonth, monthOfYear, year;
bool dateFormat;
public:
OCCCDate();
OCCCDate(int dayOfMonth, int monthOfYear, int year);
int getDayOfMonth();
int getMonth();
string getNameOfMonth();
int getYear();
string getDate();
int getDifference(OCCCDate d1, OCCCDate d2);
int getDifference(OCCCDate d1);
void setDateFormat(bool);
bool equals(OCCCDate d);
string toString();
};
#endif
And here is my OCCCDate.cpp file
#include<iostream>
#include<ctime>
#include "OCCCPerson.h"
using namespace std;
OCCCPerson::OCCCPerson(string firstName, string lastName, OCCCDate dob, string studentID):Person(firstName, lastName, dob){
string firstName = Person::getFirstName();
string lastName = Person::getLastName();
OCCCDate dob = dob;
this->studentID = studentID;
}
OCCCPerson::OCCCPerson(Person p, string studentID){
Person p = p;
this->studentID = studentID;
}
What you need is member initializer lists.
From cppreference:
In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual base subobjects and non-static data members.
A simple example:
class MyClass : BaseClass
{
public:
MyClass(int arg) : BaseClass(arg) {
//Rest of code
}
}
In your case, you can do:
OCCCPerson(string firstName, string lastName, OCCCDate dob, string studentID) :
Person(firstName, lastName, dob) {
this.studentID = studentID;
}
In OCCCPerson.cpp,
OCCCPerson(string firstName, string lastName, OCCCDate dob, string
studentID) : Person(firstName, lastName, dob)
{
//more stuff
}
You basically have to use an initializer list.
Read more here: What are the rules for calling the superclass constructor?
What this does is it calls the parent constructor Person(string, string, OCCCDate) and basically performs this->firstName = firstName. Similarly for lastName and dob. But not studentID because the Person(string, string, OCCCDate) constructor doesn't provide initialization for studentID.

What's wrong with this? Setters/Getters (edited ) header files included

when I have the following member in a class
employee headOfDepartment;
what's wrong these setters and getters?
void department::setHeadOfDepartment( employee depEmployee)
{
headOfDepartment=depEmployee;
}
employee department::getHeadOfDepartment()
{
return headOfDepartment;
}
I've been trying forever to define setters & getters with composition and it keeps getting me this error: "field ‘headOfDepartment’ has incomplete type"
ok Those are the header files:
#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_
using namespace std;
#include <iostream>
#include <vector>
#include "department.h"
#include "project.h"
class department;
class project;
//#include <vector>
employee.h
class employee
{
string Name; //text with spaces
string National_ID; //unique value (text) for each employee
static double Salary; // value of 1500 pounds
char Gender; //character holds f or m
int Available_vacations; //initially starts with 15 days
static double Deduction_per_day; // value of 85.5 pounds
int Available_permission_hours; //initially starts with 20 hours
static double Deduction_per_hour; // value of 15.5 pounds
double Actual_salary; // value with actual salary after deductions
int Vacations; // vacations employee took
int Permessions; // permession hours employee took
int empSerialNum; // object order in vector
department* myDepartment;
vector < project > empProjects;
public:
employee (); // default constructor
employee (string myName, string myNationalID, char myGender,int mySerialNum); // Parameterized constructor
~employee(); // Destractor
//Setters
void setName(string myName);
void setNationalID (string myNationalID);
void setGender (char myGander);
void setAvailableVacation(int myAvVac);
void setAvailablepermissionhours (int myAvPerHours);
void setActualSalary (double actualSalary);
void setVacations(int myVacations);
void setPermessions(int myPermessions);
void setempSerialNum(int mySerialNum);
void setDepartment(department*);
void addProject(project);
//Getters
string getName();
string getNationalID ();
char getGender ();
int getAvailableVacation();
int getAvailablepermissionhours ();
double getActualSalary ();
int getVacations ();
int getPermessions ();
int getempSerialNum();
department* getDepartment();
project* getProjects();
void view (); // View to view Name, ID and actual salary
void View_Detailed (); //call previous function and also shows other details (vacations - permissions - detailed deductions - ... )
void Free_All(); //return all values to default
double Take_vacation(); //this function takes number of days employee need to take as vacation, available vacations reduced by number of days given, if available vacations became 0 salary is deduced by deduction per day set
double Take_permession(); //this function takes hours that employee asked to take, reduce available permission hour by hours given, if available permission become 0 hour salary is reduced by deduction per ho
double Calculate_Actual_Salary();// calculates salary after deductions and returns it
};
#endif
department.h
#ifndef DEPARTMENT_H_
#define DEPARTMENT_H_
using namespace std;
#include <string.h>
#include "employee.h"
#include "project.h"
#include <vector>
class project;
class employee;
class department{
private:
string name;
string ID;
employee headOfDepartment;
vector <project> depprojects; //projects managed by the department
public:
//constructors
department();
department(string, string);
//Setters
void setName(string);
void setID(string);
void setHeadOfDepartment( employee /*const&*/ depEmployee);
void addProject(project);
//Getters
string getName();
string getID();
employee getHeadOfDepartment() /*const*/;
// project getProjects();
};
#endif
project.h
#ifndef PROJECT_H_
#define PROJECT_H_
#include <string.h>
#include "department.h"
#include "project.h"
class department;
class project{
string name;
department* location;
public:
//constructors
project();
project(string proName, department* proDepartment);
//Setters
void setName(string proName);
void setLocation(department* proDepartment);
//Getters
string getName();
department* getLocation();
};
#endif
You need to the include the header file where employee is declared in your header and source files for department
Class employee shall be defined before using it as a type name of an object. Also I advice to add qualifier const for the getter
You are not including the header that defines employee in your department class header, but you have a non-reference non-pointer declaration of type employee in your header.

Unable to use member function inside a class

I am currently learning about classes and am having a problem in my class implementation file.
In my class header/specification file Book.h , I have the public member function setPages.
#ifndef BOOK_H
#define BOOK_H
#include <string>
#include "Author.h"
#include "Publisher.h"
class Book
{
private:
std::string _title;
std::string _edition;
int _pages;
int _copyrightYear;
Author _author;
Publisher _publisher;
public:
Book (std::string title, Author author, Publisher publisher)
{_title = title; _author = author; _publisher = publisher;}
void setPages (int pages);
void setCopyYear (int copyrightYear);
void setEdition (std::string edition);
std::string getTitle () const;
std::string getEditon () const;
int getPages () const;
int getCopyYear () const;
Author getAuthor () const;
Publisher getPublisher () const;
};
#endif
In my Book.cpp implementation file I have
#include <string>
#include "Author.h"
#include "Publisher.h"
#include "Book.h"
void Book::setPages (int pages)
{
_pages = pages;
}
I keep getting the error that Book is not a classname or namespace but I don't see what I've done wrong. I included my Book header file and checked to make sure everything was spelled correctly in the class. I've done the same thing in my other classes and it is working so I don't see why this isn't.
Any help appreciated thanks.
Here is Publisher.h and Author.h
#ifndef PUBLISHER_H
#define PUBLISHER_H
class Publisher
{
private:
std::string _name;
std::string _address;
std::string _phoneNumber;
public:
Publisher (std::string& name)
{_name=name;}
void setAddress (std::string address);
void setNumber (std::string phoneNumber);
std::string getAddress () const;
std::string getNumber () const;
bool operator==(std::string name)
{
if (_name == name)
return true;
else
return false;
};
#endif
and Author.H
#ifndef AUTHOR_H
#define AUTHOR_H
class Author
{
private:
std::string _name;
int _numberOfBooks;
public:
Author(std::string& name)
{_name = name;}
void setNumOfBooks (int numberOfBooks);
int getNoOfBooks () const;
bool operator==(std::string _name)
{
if (this->_name == _name)
return true;
else
return false;
}
};
#endif
Until #ahenderson decides to turn his comments into an answer:
bool operator==(std::string name) in "Publisher.h" is missing a brace in your example. is that actually in your code or a copy and paste error?
bool operator==(std::string name)
{
if (_name == name)
return true;
else
return false;
Oops, no brace here!
Suggestion: Simplify your operator== method:
The expression _name == name will already return true or false. No need to put it into an if clause that returns true or false.
Try this:
bool operator==(const std::string& name)
{
return (_name == name);
}
In the above example, the expression is evaluated and the result is returned, directly.
Also, you may run into compiler issues if your variables begin with an underscore, '_'. Change your naming convention so this issue doesn't raise its ugly head. Two common practices are to append a suffix, name_, or prefixing with something like m_name.