C++ Error "Undefinded reference to 'Student::Student - c++

Hey Guys I could really use some help here. I am in a intro to C++ class, and have been trying my best to figure out this whole programming thing out. In one of my assignments i am getting an "undefined reference to" error in my program. It is coming up on line 30 of the main.cpp file. The line that creates a new student object called student1 using the constructor student. Any help figuring out the root of this problem would be greatly appreciated.
Thank you in advance!!
Student.h
#ifndef STUDENT_H_INCLUDED
#define STUDENT_H_INCLUDED
#include <string>
using namespace std;
class Student
{
private:
//instance variables declaration
// declare an int variable called studentID
int studentID;
// declare a string variable called firstName
// declare a string variable called lastName
string firstName;
string lastName;
// declare a string variable called major
string major;
// declare an int variable called gradePoints
int gradePoints;
// declare an int variable called totalCredits
int totalCredits;
public:
//member function declaration
Student(int , string , string , string , int , int );
//function getId() is the accessor for instance variable studentID
int getID();
//function getFullName() is the accessor for both firstName and lastName
//you will need to use string concatenation to return the student full name
string getFullName();
//function getMajor() is the accessor for instance variable major
string getMajor();
//function getGradepoints() is the accessor for instance variable gradePoints
int getGradepoints();
//function getCredits() is the accessor for instance variable totalCredits
int getCredits();
//function changeMajor(string ) is the mutator for instance variable major
//the function declaration is given as below
void changeMajor(string newMajor);
//function changeMajor(string, int, int) is an overloadded mutator for major
//the function declaration is given as below
void changeMajor(string newMajor, int newPoints, int newCredits);
//function toString() is used to print out all instance variables value
string toString();
};
#endif // STUDENT_H_INCLUDED
Student.cpp
#include "Student.h"
#include <iostream>
#include <sstream>
using namespace std;
Student::Student(int id, string fName, string lName, string major, int points, int credits)
{
studentID = id;
// write the segment of codes that assign input parameters to each of the instance variables
firstName=fName;
lastName=lName;
major=major;
gradePoints=points;
totalCredits=credits;
}
int Student::getId()
{
// write a line of code that returns the studentID
return studentID;
}
string Student::getFullName()
{
// write a line of code that returns the full name of the student, includes both first and last name.
stringstream ss;
ss<<firstName<<" "<<lastName;
return ss.str();
}
string Student::getMajor()
{
// write a line of code that returns the student's major
return major;
}
int Student::getGradepoints()
{
// write a line of code that returns the student grade points
return gradePoints;
}
int Student::getCredits()
{
// write a line of code that returns the student total credits
return totalCredits;
}
void Student::changeMajor(string newMajor)
{
// Change the value of the Student’s major variable to the new input’s value.
major=newMajor;
}
void Student::changeMajor(string newMajor, int newPoints, int newCredits)
{
// If newPoints and newCredits are less than or equal to their respective instance variable, update
// the student’s major variable to its new major. Otherwise, print an error message 'Invalid attempt'
major=newMajor;
gradepoints=newPoints;
totalCredits=newCredits;
}
string Student::toString()
{
stringstream ss;
ss<<"==================================="<<endl;
ss<<"Student ID :"<<getID()<<endl;
ss<<"Student Name :"<<getFullName()<<endl;
ss<<"Major :"<<getMajor()<<endl;
ss<<"Num. of Points :"<<getGradepoints()<<endl;
ss<<"Total Credits :"<<getCredits()<<endl;
return ss.str();
}
main.cpp
#include <iostream>
using namespace std;
#include "Student.h"
int main()
{
//declare variables where you will store inputs from user
int studentID;
string firstName;
string lastName;
string major;
int gradePoints;
int totalCredits;
//prompt the user for inputs studentID, firstName, lastName, major
//gradePoints and totalCredits.
//store the input in the declared variables
cout << "Enter student ID: ";
cin>>studentID;
cout << "Enter first name: ";
cin>>firstName;
cout << "Enter last name: ";
cin>>lastName;
cout << "Enter student major: ";
cin>>major;
cout << "Enter # of Points: ";
cin>>gradePoints;
cout << "Enter # of credits: ";
cin>>totalCredits;
//use the constructor with arguments to create a brand-new Student object
//called student1 using the variable values provided by the user
Student student1(studentID,firstName,lastName,major,gradePoints,totalCredits);
//call the getFullName() function to get the full name of the student.
cout << "\nStudent Name:\t" <<student1.getFullName()<<"\n";
//call the getId() method to get the ID of the student
cout <<"\nStudent ID:\t" << student1.getID() << "\n";
//call the toString() method to get every info. of the student
//show it on screen
cout << student1.toString() << endl;
//Attempt to change the major to 'International Affairs' with 10 points and 500 credits
//by calling changeMajor(String newMajor, int newPoints, int newCredits) function
//This should not succeed. It should print the 'Invalid attempt" message.
student1.changeMajor("International Affairs,10,500");
//call getMajor() method and store the student's old major
//into a variable oldMajor
string oldMajor =student1.getMajor();
//Change just the student’s major to
//'International Affairs' by calling changeMajor(String newMajor) function
student1.changeMajor("International Affairs");
// Print out the following message on screen
// <Student full name> has changed major from <Student_old_major> to <Student_new_major>
cout<<student1.getFullName()<<" has changed major from "<<oldMajor<<" to "<<student1.getMajor()<<endl;
//call toString() function to print student1 info. again on screen
cout<<student1.toString()<<endl;
}
I am using a GNU GCC Compiler to compile the program.

I think maybe here's the solution:
"This task tells g++ to take the active file (${file}), compile it, and create an executable file in the current directory (${fileDirname}) with the same name as the active file but without an extension (${fileBasenameNoExtension}), resulting in helloworld for our example."

Related

Why are some of my elements not displaying in my final output?

I'm trying to set my values for my variables to be displayed in my output, but only one variable's value is managed to display in my output. Is it because there is some error in my get, set method in my class defining?
#include <iostream>;
#include <string>;
using namespace std;
class Employee
{
private:
string name;
int idNumber;
string department;
string position;
public:
void setEmployee(string nam, int id, string dep, string pos);
string getEmployee();
};
void Employee::setEmployee(string nam, int id, string dep, string pos)
{
name = nam;
idNumber = id;
department = dep;
position = pos;
}
string Employee::getEmployee()
{
return name, idNumber, department, position;
}
int main()
{
Employee emp;
cout << "Name \t" << "ID Number \t" << "Department \t" << "Position" << endl;
emp.setEmployee("Susan", 47899, "Accounting", "Vice President");
cout << emp.getEmployee();
return 0;
}
The error is here:
return name, idNumber, department, position;
In C++ a function can return only one single value.
Your getEmpoyee() function is defined to return one single string, and that is exactly what it does.
Using comma the way you do is a valid syntax so it compiles, but it does not do what you think. Everything after name is simply ignored.
The proper way is to create separate get functions for all fields.
It is also recommended to use separate set functions, each setting only one field.
If you want to initialize all fields at once, you should do it in the constructor.
Example:
class Employee
{
private:
string name;
int idNumber;
string department;
string position;
public:
//this is a constructor, it has no return type and same name as the class
Employee(string nam, int id, string dep, string pos);
string getEmployee();
};
Employee::Employee(string nam, int id, string dep, string pos)
{
name = nam;
idNumber = id;
department = dep;
position = pos;
}
int main() {
Employee emp("Susan", 47899, "Accounting", "Vice President");
}
This line
return name, idNumber, department, position;
Will return only name. If you want to return one string containing all values, you have to concatenate the values into one string, e.g. by using the + operator.

Can't convert string to int in return. No string variable declared whatsoever in int returning function getsocial()

#include<iostream>
#include<string>
using namespace std;
/*this program takes a bank customer's info with the use of a class*/
//class definition
class BankCustomer
{
public:
BankCustomer(); //constructor for BankCustomer class
void fullname(string, string);
string firstname();
string lastname();
bool setsocial(int s); //accept a arg. of int type
int getsocial();
private:
string fname, lname, SSNlength; //can't be changed by client; sensitive info should be made private
};
//class implementation
BankCustomer::BankCustomer(){}
void BankCustomer::fullname(string f, string l)
{
fname=f;
lname=l;
}
string BankCustomer::firstname()
{
return fname;
}
string BankCustomer::lastname()
{
return lname;
}
bool BankCustomer::setsocial(int s)//function verifies that entered SSN is 9 digits long by counting # of digits of entered SSN
{
int count, SSNlength;
while(s != 0)
{
s /=10;
++count;
if(count == 9)
{
cout <<"\nValid SSN Entered!" << endl;
SSNlength=s;
return true;
}
}
}
int BankCustomer::getsocial()
{
return SSNlength;
}
//client program
int main()
{
BankCustomer customer; //customer declared as object of BankCust class
string firstname, lastname;
int ssn, s;
//data assignment
cout <<"\n Enter First Name\n" << endl;
cin >> firstname;
cout<<"\n Enter Last Name\n"<< endl;
cin >> lastname;
customer.fullname(firstname,lastname);
do
{
cout<<"\nEnter 9-Digit SSN"<< endl;
cin >> ssn;
customer.setsocial(ssn);
}
while(!customer.setsocial(ssn)); //function will repeat as long as entered user ssn forces setsocial() to evaluate it as false
//data ouput
cout <<"\nFirst Name: "<<customer.firstname()<<"\n"<< endl;
cout <<"\nLast Name: "<<customer.lastname()<<"\n"<< endl;
cout <<"\n SSN is: "<<customer.getsocial()<<"\n" << endl;
}
The error is targeting BankCustomer::getsocial(). The variable SSNlength is declared as an int type and getsocial() has a return type of int. I don't see anywhere in my code where I intend to convert SSNlength to a string. Is it how I'm passing and handling data with the setsocial() function?
That is wrong:
int BankCustomer::getsocial()
{
return SSNlength;
}
since SSNlength is a member variable of the class BankCustomer of type string, visible from BankCustomer::getsocial, even if not declared in the method. That how C++ works.
So the compiler complains that it cannot convert a string to an int (what you want to return).
this is where you declare it:
private:
string fname, lname, SSNlength; //can't be changed by client; sensitive info should be made private
Given the name of the variable, I suspect that you wanted to write:
private:
string fname, lname;
int SSNlength; //can't be changed by client; sensitive info should be made private
be careful, there's an auto variable called the same way in another method.
I suggest a naming rule for members to avoid all that. Example: prefix all members with m_:
private:
string m_fname, m_lname
int m_SSNlength; //can't be changed by client; sensitive info should be made private

How do I use the ostream::seekp function to find an object with a certain id# in a random access file?

I have a Person class that has the private data members id, lastName, firstName, and age. I created file containing 50 Person objects with "unassigned" and 0 for the data members, using this function:
void createPersonFile(ofstream &outputPersonFile){
Person blankPerson;
blankPerson.setID(0);
blankPerson.setFirstName("unassigned");
blankPerson.setLastName("unassigned");
blankPerson.setAge(0);
for (int x = 0; x < 50; x++)
outputPersonFile.write(reinterpret_cast<const char *>(&blankPerson),
sizeof(Person));
}
I have to create functions that will let me write a new Person, update a Person, delete a Person, and display a Person but I don't know how to use the seekp function to write them. This is what I have for a function that will write a new Person to the file. I already have two separate functions not shown here that I am calling to open input/output files.
void writeNewPerson(ofstream &outputPersonFile){
int inputID;
int userNumber;
string userInput;
Person person;
cout << "Please enter a record number (1-50): ";
cin >> inputID;
cout << "Enter the person's first name: ";
cin >> userInput;
person.setFirstName(userInput);
cout << "Enter the person's last name: ";
cin >> userInput;
person.setLastName(userInput);
cout << "Enter the person's age: ";
cin >> userInput;
person.setAge(userNumber);
cout << endl;
outputPersonFile.seekp( WHAT GOES HERE??? );
outputPersonFile.write( reinterpret_cast<const char*>(&person), sizeof(Person) );
}
I'm stumped on how to use the seekp function above...
Person.h
// Person.h
// Class Person definition
#ifndef PERSON_H
#define PERSON_H
#include <string>
using namespace std;
class Person
{
public:
// default Person constructor
Person(int = 0, string = "unassigned", string = "unassigned", int = 0);
// accessor functions for id
void setID(int);
int getID() const;
// accessor functions for lastName
void setLastName(string);
string getLastName() const;
// accessor functions for firstName
void setFirstName(string);
string getFirstName() const;
// accessor functions for age
void setAge(int);
int getAge() const;
private:
int id;
char lastName[15];
char firstName[15];
int age;
}; // end class Person
#endif

using code blocks for c++ I'm trying to print out an accessor function from my class. the error states that request for member get_address

This is my code it includes the main, header and source file I'm trying to print out an accessor function from my class AddressSpace, but its saying that
request for member "get_address" in "ob", which is of non-class type AddressSpace(std::string, std::string, std::string, int) {aka AddressSpace(std::basic_string, std::basic_string, std::basic_string, int)}
main.cpp
#include <iostream>
#include <string>
#include "AddressSpace.h"
#include "AddressSpace.cpp"
using namespace std;
int main()
{
string address;
string town;
string state;
int postal;
cout << "What is the street you live on?: " <<endl;
cin >> address;
cout << "What is the city you live in?: " <<endl;
cin >> town;
cout <<"What is the state you live in?: " << endl;
cin >> state;
cout << "What is the postal code?: " << endl;
cin >> postal;
AddressSpace ob(string address,string town,string state,int postal);
cout << "Address" << ob.get_address() << endl;
return 0;
}
AddressSpace.h
#ifndef ADDRESSSPACE_H_INCLUDED
#define ADDRESSSPACE_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
class AddressSpace{
public:
//Default constructor
AddressSpace();
//overload constructor
AddressSpace(string, string, string, int);
//Accessor Functions
string get_address() const;
// get_address - returns address
string get_town() const;
// get_town -returns town
string get_state() const;
// get_state - returns state
int get_postal() const;
// get_postal returns zip code
private:
//member variables
string street;
string city;
string st;
int zip;
};
#endif // ADDRESSSPACE_H_INCLUDED
AddressSpace.cpp
#include "AddressSpace.h"
AddressSpace::AddressSpace(string address, string town, string state, int postal){
string street = address;
string city = town;
string st = state;
int zip = postal;
}
string AddressSpace::get_address() const {
return street;
}
string AddressSpace::get_town() const {
return city;
}
string AddressSpace::get_state() const {
return st;
}
int AddressSpace::get_postal() const {
return zip;
}
The following line of code in main() is a function declaration or prototype.
AddressSpace ob(string address,string town,string state,int postal);
If you remove the type names inside the parentheses it will do what you intended, to construct an object named ob using the given parameters.
AddressSpace ob(address, town, state, postal);
When declaring a new object you don't prefix it with the type. You also haven't instantiated the strings or integer. In C/C++ un-instantiated values are random, so it's good practice to give every variable a default value. You should also include the code for AddressSpace.h and AddressSpace.cpp so we have a better idea of what else could be going wrong
Also, notice the change to the parameters of main(). It's not necessary, but considered good form to always include it. These arguments are filled in with the number of arguments and the arguments themselves if your program is run from the command line.
Your code should look more like this I think:
#include <iostream>
#include <string>
#include "AddressSpace.h"
//#include "AddressSpace.cpp" //This line isn't needed, you should only include the header file
using namespace std;
int main(int argc, char** argv)
{
string address = "";
string town = "";
string state = "";
int postal = 0; //Note postal codes for Europe include letters, and you most-likely won't be doing math with a zipcode so it might make more sense to make it a string
cout << "What is the street you live on?:" << endl;
cin >> address;
cout << "What is the city you live in?:" << endl;
cin >> town;
cout << "What is the state you live in?:" << endl;
cin >> state;
cout << "What is the postal code?:" << endl;
cin >> postal;
AddressSpace ob(address, town, state, postal);
cout << "Address " << ob.get_address(); << endl;
return 0;
}

c++ program outputs series of numbers instead of cout

My current assignment is to create a simple
Student Class that takes the
first name
last name
student ID number
from an object and outputs the name as a single string and his/her ID number. The program also has to count every student and output the total number of students. In this program I'm given 4 students.
I've created the program, given below. Everything compiles correctly and runs but my output is strange. Instead of giving me the students' ID and name, it gives me the number "-858993460". I have no idea why my program's doing this and a long search on the internet hasn't helped me much.
Student.h
#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string firstName;
string lastName;
int id;
string name;
public:
static int numberOfStudents;
Student();
Student(string theFirstName, string theLastName, int theID);
string getName();
int getID();
};
Student.cpp
#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
//initialize numberOfStudents to 0
int Student::numberOfStudents = 0;
//initialize default constructor
Student::Student()
{
numberOfStudents++;
}
//initialize overloaded constructor
Student::Student(string theFirstName, string theLastName, int theID)
{
theFirstName = firstName;
theLastName = lastName;
theID = id;
numberOfStudents++;
}
//getName
string Student::getName()
{
return firstName += lastName;
}
//getID
int Student::getID()
{
return id;
}
main.cpp(this is my driver file)
#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
Student st1("Hakan", "Haberdar", 1234), st2("Charu", "Hans", 2345), st3("Tarikul", "Islam", 5442), st4;
cout << "We created " << Student::numberOfStudents<<" student objects." << endl;
cout << st1.getID()<<" "<<st1.getName()<<endl;
cout << st2.getID()<<" "<<st2.getName()<<endl;
cout << st3.getID()<<" "<<st3.getName()<<endl;
cout << st4.getID()<<" "<<st3.getName()<<endl;
system("pause");
};
This is what my output is supposed to look like:
We created 4 student objects.
1234 Hakan Haberdar
2345 Charu Hans
5442 Tarikul Islam
0
This is what my output instead looks like:
We created 4 student objects.
-858993460
-858993460
-858993460
-858993460
I think my problem has something to do with my getName() function, but I'm not sure and I don't know what to try.
Student::Student(string theFirstName, string theLastName, int theID)
{
theFirstName = firstName;
theLastName = lastName;
theID = id;
numberOfStudents++;
}
Your assignments are the wrong way round. You're assigning the as yet uninitialised members to the arguments. Instead you should have:
Student::Student(string theFirstName, string theLastName, int theID)
{
firstName = theFirstName;
lastName = theLastName;
id = theID;
numberOfStudents++;
}
This mistake would have been avoided if you had used a member initialization list instead:
Student::Student(string theFirstName, string theLastName, int theID)
: firstName(theFirstName), lastName(theLastName), id(theID)
{
numberOfStudents++;
}
Not sure if the following is the reason for your issues, but it does seem wrong...
return firstName += lastName;
What this does is modifies firstname by appending last name to it, then returning modified string.
I think you meant to do something like
return firstName << ' ' << lastName;
Change your code to.
Student::Student(string theFirstName, string theLastName, int theID)
{
firstName = theFirstName;
lastName = theLastName;
id = theID;
numberOfStudents++;
}
Your code returning the value of id! which is not initialized.
So the code will return garbage.