Passing an object as argument in c++ - c++

Iam new to c++ trying to learn about namespaces and class.
I have 2 classes here Both are in different files.
The first one is
#include<iostream>
using namespace std;
namespace project{
class Student{
string name,address,enrolmentDate ,usn;
int hours;
public:
Student(char* nusn, char* nname, char* naddress, char* ndate,int nhours){
usn = nusn;
name = nname;
address = naddress;
enrolmentDate = ndate;
hours = nhours;
}
Student(){
getData();
}
void getData(){
std::cout << "Enter Usn,Name,Address,EnrolmentDate,Hours\n";
std::cin >> usn >> name >> address >> enrolmentDate >> hours;
}
string getName(){
return name;
}
string getAddress(){
return address;
}
string getenrolmentDate(){
return enrolmentDate;
}
int getHours(){
return hours;
}
string getUsn(){
return usn;
}
};
}
The Second class is
#include<iostream>
using namespace std;
namespace project{
class CourseRegistration{
string usn, courseId ;
int hours, grade;
public:
CourseRegistration(project::Student obj, string courseId, int nhours, int ngrade){
usn = obj.getUsn();
this->courseId = courseId;
hours = nhours;
grade = ngrade;
}
};
}
The First class Compiles fine.But the second class gives an error.
The error is near that Student Object.
Course.cpp:10:38: error: expected ‘)’ before ‘obj’
CourseRegistration(project::Student obj, string courseId, int nhours, int ngrade){
How Do i Correct It?

I do not see any evidence you've included the definition of Student in "the second file." Your class should be delclared in a header (.h) file with the implementation in a source (.cpp) file. Your compiler is likely complaining because it doesn't know that Student is a class.
Student.h
#include<iostream>
using namespace std;
namespace project {
class Student {
private:
string name,address,enrolmentDate, usn;
int hours;
public:
Student( char*, char*, char*, char*, int );
Student();
void getData();
string getName();
string getAddress();
string getenrolmentDate();
int getHours();
string getUsn();
}
}
Student.cpp
#include "Student.h"
namespace project {
Student::Student( char* nusn, char* nname, char* naddress, char* ndate,int nhours ) {
usn = nusn;
name = nname;
address = naddress;
enrolmentDate = ndate;
hours = nhours;
}
Student() {
getData();
}
void getData() {
std::cout << "Enter Usn,Name,Address,EnrolmentDate,Hours\n";
std::cin >> usn >> name >> address >> enrolmentDate >> hours;
}
string getName() {
return name;
}
string getAddress() {
return address;
}
string getenrolmentDate() {
return enrolmentDate;
}
int getHours() {
return hours;
}
string getUsn() {
return usn;
}
}
CourseRegistration.h
#include "Student.h"
#include<iostream>
using namespace std;
namespace project{
class CourseRegistration {
private:
string usn, courseId ;
int hours, grade;
public:
CourseRegistration( Student, string, int, int );
}
}
CourseRegistration.cpp
#include<CourseRegistration.h>
namespace project {
CourseRegistration::CourseRegistration( Student obj, string courseId, int nhours, int ngrade ) {
usn = obj.getUsn();
this->courseId = courseId;
hours = nhours;
grade = ngrade;
}
}

Related

Class Employee ID count c++ [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 4 years ago.
I'm editing it, now ok i apply an empty constructor and my code worked but this way:
Name1 SName1 1000 0.2 100
Name2 SName2 1000 0.3 750
This code normally works perfectly and my teacher especially wants us to use "this->" and "*this" so here's my code:
my .h file
#ifndef COMEMPLOYEE_H
#define COMEMPLOYEE_H
#include <string>
using namespace std;
class ComEmployee
{
protected:
string firstName;
string lastName;
static int ID;
double grossSale;
double comRate;
public:
ComEmployee();
ComEmployee(string, string, double, double);
ComEmployee& setfirstName(string);
ComEmployee& setlastName(string);
ComEmployee& setgrossSale(double);
ComEmployee& setcomRate(double);
string getfirstName();
string getlastName();
double getgrossSale();
double getcomRate();
int getID() const;
double calCom() const;
void Display() const;
};
#endif
my .cpp file
#include "ComEmployee.h"
#include <iostream>
using namespace std;
int ComEmployee::ID = 1000;
ComEmployee::ComEmployee(){}
ComEmployee::ComEmployee(string name, string lname, double gs, double comr)
{
this->firstName = name;
this->lastName = lname;
this->grossSale = gs;
this->comRate = comr;
++ID;
}
int ComEmployee::getID() const
{
return ID;
}
ComEmployee & ComEmployee::setfirstName(string name)
{
firstName = name;
return *this;
}
ComEmployee & ComEmployee::setlastName(string lname)
{
lastName = lname;
return *this;
}
ComEmployee & ComEmployee::setgrossSale(double gs)
{
grossSale = gs;
return *this;
}
ComEmployee & ComEmployee::setcomRate(double comr)
{
comRate = comr;
return *this;
}
string ComEmployee::getfirstName()
{
return firstName;
}
string ComEmployee::getlastName()
{
return lastName;
}
double ComEmployee::getgrossSale()
{
return grossSale;
}
double ComEmployee::getcomRate()
{
return comRate;
}
double ComEmployee::calCom() const
{
return grossSale*comRate;
}
void ComEmployee::Display() const
{
cout << firstName << " " << " " << getID() << " " << comRate << " " << calCom() << endl;
}
here's my main.cpp file
#include <iostream>
#include "ComEmployee.h"
using namespace std;
int main()
{
ComEmployee employee, employee2;
employee.setfirstName("Name1").setlastName("SName1").setgrossSale(500).setcomRate(0.2).Display();
employee2.setfirstName("Name2").setlastName("SName2").setgrossSale(2500).setcomRate(0.3).Display();
system("pause");
}
I want my output as:
Name1 SName1 1001...
Name2 SName2 1002...
You have to change your design a bit. As ID is employee ID, it cannot be a static variable. A static variable belongs to the class rather than to particular instance of
the class.
Define ID as a normal member of the class.
You can use a new static variable CurrentID instead to keep track of the employees.
After defining it like below,
int ComEmployee::CurrentID = 1000;
In the default and non-default constructors, do the following:
this->ID = CurrentID++;
Add some int variable to your class definition:
int m_ID;
Then, you need to emplement a default constructor in cpp-file:
// cpp
ComEmployee::ComEmployee()
{
m_ID = ID++;
}
And modify your GetID function:
int ComEmployee::GetID() const
{
return m_ID;
}

C++ Access error, pointer trouble

I'm working on saving objects to a file and reading them back out. Right now I'm trying to do them one at a time to see if I can do and avoid duplicate objects. I'm getting this error: Exception thrown at 0x00915B18 in who.exe: 0xC0000005: Access violation writing location 0xDDDDDDDD
I know that this is because I'm not doing something with a pointer correctly but I'm lost and can't quite figure it out, current code is:
#include<iostream>
#include "Book.h"
#include "InventoryBook.h"
#include "SoldBook.h"
#include<string>
#include<fstream>
using namespace std;
void saveBook(Book);
Book returnBook();
void main() {
Book novel;
InventoryBook shelf;
SoldBook gone;
novel.setAuthor("Joe");
novel.setISBN("1234567788");
novel.setPublisher("Me");
novel.setTitle("Joe vs. the Volcano");
saveBook(novel);
Book rBook = returnBook();
cout << rBook.getAuthor();
system("Pause");
}
void saveBook(Book saved) {
ofstream myfile;
myfile.open("bookInventory.txt", ios::app);
myfile.write((char*)&saved, sizeof(saved));
}
Book returnBook() {
ifstream myfile;
myfile.open("bookInventory.txt", ios::in);
Book novel;
Book newBook;
myfile.read((char*)&novel, sizeof(novel));
newBook.setAuthor(novel.getAuthor());
return newBook;
}
I know that the save book function works and that I run into my issues with the returned book object. I'm just not able to see where this goes wrong. I'm a little fuzzy on pointers.
#pragma once
#ifndef BOOK_H
#define BOOK_H
#include<iostream>
using namespace std;
class Book{
private:
string ISBN;
string bookTitle;
string authorName;
string publisher;
public:
Book(string, string, string, string);
Book();
//destructor
~Book();
//Mutators
void setTitle(string);
void setISBN(string);
void setAuthor(string);
void setPublisher(string);
//accessors
string getTitle();
string getISBN();
string getAuthor();
string getPublisher();
};
#endif
#include "Book.h"
Book::Book() {
ISBN = "";
bookTitle = "";
authorName = "";
publisher = "";
}
Book::Book(string newISBN, string newTitle, string newAuthor, string newPub) {
ISBN = newISBN;
bookTitle = newTitle;
authorName = newAuthor;
publisher = newPub;
}
Book::~Book()
{
}
void Book::setISBN(string newISBN) {
ISBN = newISBN;
}
string Book::getISBN() {
return ISBN;
}
void Book::setTitle(string newTitle) {
bookTitle = newTitle;
}
string Book::getTitle() {
return bookTitle;
}
void Book::setAuthor(string newAuthor) {
authorName = newAuthor;
}
string Book::getAuthor() {
return authorName;
}
void Book::setPublisher(string newPub) {
publisher = newPub;
}
string Book::getPublisher() {
return publisher;
}

c++ printing object and constructor

Hello everyone I had a problem while running the following program in the last loop it only print three 0 without displaying any result I am not sure what is wrong with the program,perhaps it has something to do with the constructor, however when I write my getter method in the second last loop with setter method it display the correct result. any help will be appreciated.
#ifndef EMPLOYEE_H_INCLUDED
#define EMPLOYEE_H_INCLUDED
#include<string>
using namespace std;
class Employee
{
private:
string name;
int idnumber;
string department;
string position;
public:
Employee(string ,int ,string ,string);
void setName(string );
void setDepartment(string);
void setPosition(string);
void setIDNumber(int);
string getName() const
{
return name;
}
string getDepartment() const
{
return department;
}
string getPosition() const
{
return position;
}
int getIDnumber() const
{
return idnumber;
}
};
#include "Employee.h";
#include <iostream>
#include <iomanip>
using namespace std;
Employee::Employee(string name ,int IDNumber ,string department ,string position)
{
name=name;
idnumber=IDNumber;
department=department;
position=position;
}
void Employee::setDepartment(string Department)
{
department=Department;
}
void Employee::setName(string Name)
{
name=Name;
}
void Employee::setPosition(string Position)
{
position=Position;
}
void Employee::setIDNumber(int Number)
{
idnumber=Number;
}
int main()
{
string name;
int IDNumber;
string department;
string position;
const int Item=3;
Employee info1(" ",0," "," ");
Employee info2(" ",0," "," ");
Employee info3(" ",0," "," ");
Employee Info[Item]={info1,info2,info3};
}
for(Employee element:Info)
{
cout<<"please enter your name "<<endl;
cin>>name;
element.setName(name);
cout<<element.getName()<<endl;
cout<<"please enter your department "<<endl;
cin>>department;
element.setDepartment(department);
cout<<element.getDepartment()<<endl;
cout<<"please enter your position"<<endl;
cin>>position;
element.setPosition(position);
cout<<element.getPosition()<<endl;
cout<<"please enter your IDNumber"<<endl;
cin>>IDNumber;
element.setIDNumber(IDNumber);
cout<<element.getIDnumber()<<endl;
}
for(Employee element:Info)
{
cout<<element.getName()<<setw(8)<<element.getDepartment()
cout<<setw(8)<<element.getPosition()<<setw(8)<<element.getIDnumber()<<endl;
}
}
for(Employee element:Info)
element is a copy of an element from Info array. You are busy filling this copy, then it gets discarded. Contents of Info remain unchanged, with empty strings all around.
Make it
for(Employee& element:Info)
Note the ampersand.

Trying to print information stored in an array of type object in C++

I'm just starting to learn object oriented programming in C++ and am having issues figuring out how to print an object that is stored inside an array. From what I know, I want to just try to try and go through the array and print out each employee object, how because objects are different than variables like int and double I'm sure it's causing a problem. Is my logic wrong, or is it just syntax? Here is my code:
Header:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using namespace std;
class Employee
{
private:
string name;
string idNumber;
string department;
string position;
int yearsWorked;
public:
Employee();
Employee(string, string);
Employee(string, string, string, string, int);
void setName(string);
void setIdNumber(string);
void setDepartment(string);
void setPosition(string);
bool setYearsWorked(int);
string getName()const;
string getIdNumber()const;
string getDepartment()const;
string getPosition()const;
int getYearsWorked()const;
};
#endif
Implementation:
#include "Employee.h"
using namespace std;
Employee::Employee()
{
string name = "";
string idNumber = "";
string department = "";
string position = "";
int yearsWorked = 0;
}
Employee::Employee(string nm, string id)
{
string name = nm;
string idNumber = id;
string department = "";
string position = "";
int yearsWorked = 0;
}
Employee::Employee(string nm, string id, string dpt, string pos, int years)
{
string name = nm;
string idNumber = id;
string department = dpt;
string position = pos;
int yearsWorked = years;
}
void Employee::setName(string nm)
{
name = nm;
}
void Employee::setIdNumber(string id)
{
idNumber = id;
}
void Employee::setDepartment(string dpt)
{
department = dpt;
}
void Employee::setPosition(string pos)
{
position = pos;
}
bool Employee::setYearsWorked(int years)
{
if (years >= 0)
{
yearsWorked = years;
return true;
}
else
return false;
}
string Employee::getName()const
{
return name;
}
string Employee::getIdNumber()const
{
return idNumber;
}
string Employee::getDepartment()const
{
return department;
}
string Employee::getPosition()const
{
return position;
}
int Employee::getYearsWorked()const
{
return yearsWorked;
}
Main:
#include <iostream>
#include <iomanip>
#include "Employee.h"
using namespace std;
const int SIZE = 3;
int main()
{
Employee emp1("Jenny Jacobs", "JJ8990", "Accounting", "President", 15);
Employee emp2("Myron Smith", "MS7571", "IT", "Programmer", 5);
Employee emp3("Chris Raines", "CR6873", "Manufacturing", "Engineer", 30);
Employee employees[SIZE] = {emp1, emp2, emp3};
for (int i = 0; i < SIZE; i++)
{
cout << employees[i] << endl;
}
system("PAUSE");
return 0;
}
Add this:
std::ostream& operator<<( std::ostream& stream, Employee const& emp )
{
return (stream << emp.getName());
}
Modify as needed.
General comments:
Do not place using namespace std; in the global namespace in a header. Keep in mind that the standard library defines very common names like distance. Which can easily lead to name collisions.
Reserve ALL UPPERCASE names for macros, to reduce the chance of name collisions and inadvertent text substitution.
Preferentially pass potentially "large" objects, such as std::string, by reference, e.g. formal argument type std::string const&, in order to avoid excessive copying. There are some exceptions to this rule when one aims for perfect code, e.g. for C++11 move semantics, but it's a good general rule.
employees[i] is of type Employee. So either you have to print like
cout<<employees[i].getName(); // so on
Or you have to overload << operator for Employee type:
ostream& operator<<(ostream& stream, Employee const& emp );
Firstly. in my machine it compiles fine
Secondly, you are doing:
string name = nm;
So name is a automatic variable, Not the member of your class. You should do like:
name = nm; // if you delete int name; line
Or,
this->name = nm;
Some changes of your code:
Employee::Employee()
: yearsWorked( 0 )
{
}
Employee::Employee(string nm, string id)
: name( nm ), idNumber( id ), yearsWorked( 0 )
{
}
Employee::Employee(string nm, string id)
: name( nm ), idNumber( id ), department( dpt ), position( pos ), yearsWorked( years ),
{
}
std::ostream & operator <<( std::ostream &os, const Employee &emp )
{
return ( os << "ID: " << emp.idNumber << ", name: " << emp.name
<< ", department: " << emp.department << ", position: " << emp.position
<< ", years worked: " << emp.yearsWorked );
}

Class Constructor error, class "classname" has no member "classname"

#ifndef RESERVATIONS_H_INCLUDED
#define RESERVATIONS_H_INCLUDED
#include <vector>
#include <string.c>
class Reservations
{
public:
Reservations::Reservations { }
Reservations(string FullName, int PhoneNum);
string getname() { return FullName; }
int getnumber() { return PhoneNum; }
private:
string FullName;
int PhoneNum;
}
#endif // RESERVATIONS_H_INCLUDED
Reservations::Reservations(string FullName, int PhoneNum) //error on this line
{
FullName = FullName;
PhoneNum = PhoneNum;
}
I get the error in the title, I don't know why it's assuming I want it to have a member of it's own class...
you included wrong header file
Change
#include <string.c>
to
#include <string>
Also use string with full namespace std.
below code should compile with minor fix:
class Reservations
{
public:
Reservations() : PhoneNum(0) {}
Reservations(std::string FullName, int PhoneNum);
std::string getname() { return FullName; }
int getnumber() { return PhoneNum; }
private:
std::string FullName;
int PhoneNum;
};
Reservations::Reservations(std::string FullName, int PhoneNum)
{
this->FullName = FullName;
this->PhoneNum = PhoneNum;
}
// Better use member initializers list
Reservations::Reservations(std::string FullName, int PhoneNum)
: FullName(FullName),
PhoneNum(PhoneNum)
{
}
Do you mean
Reservations::Reservations() { }
instead of
Reservations::Reservations { }
?
Do this:
class Reservations
{
public:
//Reservations::Reservations { }
Reservations() { }
....