Default-Constructor when splitting file - c++

got a quick question. Why does the first programm work, but not the one when i split it into header/source file? How can i fix this? (error is that there is no default-constructor for "Stud s [line 6 main.cpp]")
Here is my code:
The working one:
#include <iostream>
#include <string>
using namespace std;
class Stud {
private:
string pren, surn;
unsigned int number;
public:
Stud(string p = "", string s = "", unsigned int n = 0) : pren(p), surn(s), number(n)
{
return;
}
friend ostream& operator<<(ostream& os, Stud& st) {
os << st.number << ", " << st.pren << " " << st.surn;
return os;
}
};
int main() {
Stud s;
Stud test("x", "y", 123);
cout << s << endl;
cout << test << endl;
}
Now the splitted one:
stud.hpp:
#ifndef STUD_HPP
#define STUD_HPP
#include <iostream>
#include <string>
class Stud {
private:
std::string pren, surn;
unsigned int number;
public:
Stud(std::string, std::string, unsigned int);
friend std::ostream& operator<<(std::ostream&, const Stud&);
};
#endif
stud.cpp:
#include "stud.hpp"
Stud::Stud(std::string p = "", std::string s = "", unsigned int n = 0) : pren(p), surn(s), number(n)
{
return;
}
std::ostream& operator<<(std::ostream& os, const Stud& st) {
os << st.number << ", " << st.pren << " " << st.surn;
return os;
}
main.cpp
#include <iostream>
#include "stud.hpp"
using namespace std;
int main() {
Stud s;
Stud test("x", "y", 123);
cout << s << endl;
cout << test << endl;
}

Related

Undefined Symbol in inherited classes for member Functions C++

So I'm writing a Manager class which inherits from SalariedEmployee which inherits from Employee. I have the employee.h header file and employee.cpp header file and also for salariedemployee as shown below.
I cant seem to understand why I get the following errors when I try to compile the code of
Undefined symbol: employeessavitch::SalariedEmployee::SalariedEmployee()
Undefined symbol: employeessavitch::SalariedEmployee::SalariedEmployee()
Undefined symbol: employeessavitch::SalariedEmployee::get_salary() const
Undefined symbol: employeessavitch::Employee::get_ssn() const
Undefined symbol: employeessavitch::Employee::get_name() const
Here are my files
employee.h
#ifndef employee_h
#define employee_h
#include <string>
#include "employee.h"
using namespace std;
namespace employeessavitch
{
class Employee
{
public:
Employee();
Employee(string the_name, string the_ssn);
string get_name( ) const;
string get_ssn( ) const;
double get_net_pay( ) const;
void set_name(string new_name);
void set_ssn(string new_ssn);
void set_net_pay(double new_net_pay);
void print_check( ) const;
protected:
string name;
string ssn;
double net_pay;
};
}
#endif /* employee_h */
employee.cpp
#include <string>
#include <cstring>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include "employee.h"
using namespace std;
namespace employeessavitch
{
Employee::Employee(): name("No name yet"), ssn("No number yet"), net_pay(0)
{
//deliberately empty
}
Employee::Employee(string the_name, string the_ssn)
{
//deliberately empty
}
Employee::Employee(string the_name, string the_number): name(the_name), ssn(the_number), net_pay(0)
{
//deliberately empty
}
string Employee::get_name() const
{
return name;
}
string Employee::get_ssn() const
{
return ssn;
}
double Employee::get_net_pay() const
{
return net_pay;
}
void Employee::set_name(string new_name)
{
name = new_name;
}
void Employee::set_ssn(string new_ssn)
{
ssn = new_ssn;
}
void Employee::set_net_pay (double new_net_pay)
{
net_pay = new_net_pay;
}
void Employee::print_check( ) const
{
cout << "\nERROR: print_check FUNCTION CALLED FOR AN \n"
<< "UNDIFFERENTIATED EMPLOYEE. Aborting the program.\n"
<< "Check with the author of the program about this bug.\n";
exit(1);
}
}//employeessavitch
salariedemployee.h
#ifndef salariedemployee_h
#define salariedemployee_h
#include <string>
#include "employee.h"
#include "salariedemployee.h"
namespace employeessavitch
{
class SalariedEmployee : public Employee
{
public:
SalariedEmployee();
SalariedEmployee (string the_name, string the_ssn, double the_weekly_salary);
double get_salary() const;
void set_salary(double new_salary);
void print_check();
protected:
double salary;//weekly
};
}//employeessavitch
#endif /* salariedemployee_h */
salariedemployee.cpp
#include <iostream>
#include <string>
#include <stdio.h>
#include "salariedemployee.h"
using namespace std;
namespace employeessavitch
{
SalariedEmployee::SalariedEmployee() //: Employee(), salary(0)
{
//deliberately empty
}
SalariedEmployee::SalariedEmployee(string the_name, string the_number, double the_weekly_salary)//: Employee(the_name, the_number), salary(the_weekly_salary)
{
//deliberately empty
}
double SalariedEmployee::get_salary() const
{
return salary;
}
void SalariedEmployee::set_salary(double new_salary)
{
salary = new_salary;
}
void SalariedEmployee::print_check()
{
set_net_pay(salary);
cout << "\n__________________________________________________\n";
cout << "Pay to the order of " << get_name( ) << endl;
cout << "The sum of " << get_net_pay( ) << " Dollars\n";
cout << "_________________________________________________\n";
cout << "Check Stub NOT NEGOTIABLE \n";
void SalariedEmployee::print_check()
{
set_net_pay(salary);
cout << "\n__________________________________________________\n";
cout << "Pay to the order of " << get_name( ) << endl;
cout << "The sum of " << get_net_pay( ) << " Dollars\n";
cout << "_________________________________________________\n";
cout << "Check Stub NOT NEGOTIABLE \n";
cout << "Employee Number: " << get_ssn( ) << endl;
cout << "Salaried Employee. Regular Pay: "
<< salary << endl;
cout << "_________________________________________________\n";
}
}//employeessavitch
main.cpp
#include <iostream>
#include <cstring>
#include <string>
#include <string.h>
#include <fstream>
#include "salariedemployee.h"
#include "employee.h"
using namespace std;
namespace employeessavitch
{
class Manager: public SalariedEmployee
{
public:
Manager();
~Manager();
void addReport(SalariedEmployee employee);
friend ostream& operator <<(ostream &outs, Manager manager);
private:
SalariedEmployee *reports;
int noReport;
};
Manager::Manager()
{
noReport = 0;
}
Manager::~Manager()
{
delete[] reports;
}
void Manager::addReport(SalariedEmployee employee)
{
SalariedEmployee *report = new SalariedEmployee[noReport+1];
for(int i = 0; i < noReport; i++)
{
report[i] = reports[i];
}
report[noReport+1] = employee;
delete[] reports;
}
ostream& operator <<(ostream &outs, Manager manager)
{
for(int i = 0; i < manager.noReport; i++)
{
outs << manager.reports[i].get_name() << endl;
outs << manager.reports[i].get_ssn() << endl;
outs << manager.reports[i].get_salary() << endl;
}
return outs;
}
}
int main()
{
cout << "hello world";
return 0;
}

Multiple classes, output

i got a class for a date and a class for a point of time. Now i want to combine them. My problem is that i'm not able to get the output working, it always uses the initialized date.
Here is my code:
main.cpp
#include <iostream>
#include <iomanip>
#include "date.hpp"
#include "time.hpp"
using namespace std;
int main() {
Datum d1;
Datum d2(03, 12, 2015);
cout << "d1: " << d1 << endl;
cout << "d2: " << d2 << endl << endl;
zeit z1;
cout << "z1: " << z1 << endl;
zeit z2(d2, 23, 30);
cout << "z2: " << z2 << endl;
return 0;
}
date.cpp
#include "date.hpp"
#include <iostream>
Datum::Datum(unsigned int d, unsigned int m, unsigned int y)
{
day = d;
month = m;
year = y;
return;
}
Datum::Datum() : Datum(1, 1, 2000) { return; }
unsigned int Datum::getday() { return day; }
unsigned int Datum::getmonth() { return month; }
unsigned int Datum::getyear() { return year; }
std::ostream& operator<<(std::ostream& os, Datum& z)
{
os << z.getday() << ".";
os << z.getmonth() << ".";
os << z.getyear();
return os;
}
date.hpp
#ifndef DATUM_HPP_
#define DATUM_HPP_
#include <iostream>
class Datum {
private:
unsigned int day;
unsigned int month;
unsigned int year;
public:
Datum(unsigned int, unsigned int, unsigned int);
Datum();
unsigned int getday();
unsigned int getmonth();
unsigned int getyear();
friend std::ostream& operator<<(std::ostream&, Datum&);
};
#endif
time.cpp
#include "time.hpp"
#include <iostream>
zeit::zeit(Datum date, unsigned int h, unsigned int m)
{
std::cout << date.getday() << "." << date.getmonth() << "." << date.getyear() << std::endl;
min = m;
hour = h;
return;
}
zeit::zeit() : zeit(Datum(),0,0) { return; }
unsigned int zeit::getmin() { return min; }
unsigned int zeit::gethour() { return hour; }
std::ostream& operator<<(std::ostream& os, zeit& z)
{
os << z.date << ", ";
if (z.gethour() < 10)
os << "0" << z.gethour();
else
os << z.gethour();
os << ":";
if (z.getmin() < 10)
os << "0" << z.getmin();
else
os << z.getmin();
return os;
}
time.hpp
#ifndef ZEIT_HPP_
#define ZEIT_HPP_
#include "date.hpp"
class zeit {
private:
unsigned int min;
unsigned int hour;
Datum date;
public:
zeit(Datum, unsigned int, unsigned int);
zeit();
unsigned int getmin();
unsigned int gethour();
friend class Datum;
friend std::ostream& operator<<(std::ostream&, zeit&);
};
#endif
This is the output i get:
d1: 1.1.2000
d2: 3.12.2015
1.1.2000
z1: 1.1.2000, 00:00
3.12.2015
z2: 1.1.2000, 23:30
What am i doing wrong? Ty for any help!
You did not set the internal date of the zeit class, so it remains initialized with the default date when it gets called by the << operator. Add this line to the constructor of zeit in time.cpp:
this->date = date;

How to read data from a text file into a struct

I'm completely new to C++ and currently I'm trying to read very basic text file which look like this:
Dr John Doe
British
2
Soccer
Swimming
and my expected output should look like:
My information
Name: John Doe
Nationality: British
I have 2 hobbies:
1. Soccer
2. Swimming
My header file:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;
const int MAX = 80;
const int MAXNO = 5;
enum Title {Miss, Mrs, Mr, Dr, Unknown};
struct Date
{
int day;
int month;
int year;
};
struct MyInfo
{
char name [MAX];
char national [MAX];
int noOfHobbies;
char hobby [MAXNO][MAX];
};
void getMyInfo (fstream& , char[] , MyInfo&);
void displayMyInfo (MyInfo);
My functions:
#include "Lab_1.h"
void getMyInfo (fstream& afile,char fileName[], MyInfo& x) {
afile.open (fileName);
if (!afile)
{
cout << "Binary file " << fileName << " opened for creation failed" << endl;
exit (-1);
}
cout << "\n" << "Begin reading of " << fileName << endl;
string line;
while(getline(afile, line))
{
afile >> x.national;
afile >> x.noOfHobbies;*/
if (afile >> x.name >> x.national >> x.noOfHobbies) {
cout << "Name: " << x.name << ", "
<< "National: " << x.national << ", "
<< "noOfHobbies: " << x.noOfHobbies << ", "
<< endl;
}
}
}
void displayMyInfo (MyInfo x) {
}
My main function:
#include "Lab_1.h"
int main () {
fstream afile;
MyInfo x;
string fileName;
getMyInfo(afile,"textfile.txt",x);
//displayMyInfo(x);
afile.close ();
}
The above code output nothing because I just put everything I understand over the forum with similar question. Since I'm already stuck for 1 day even though I've already done a lot of research but most of them suggest to use vector which I'm not familiar with at this moment, so can someone give me a solution to this problem? Thank you very much for your help in advance.
Random act of madness kindness:
Live On Coliru
#include <fstream>
#include <set>
struct Person {
std::string name;
std::string nationality;
std::set<std::string> hobbies;
friend std::istream& operator>>(std::istream& is, Person& into) {
size_t n = 0;
if (getline(is, into.name) &&
getline(is, into.nationality) &&
is >> n && is.ignore(1024, '\n'))
{
while (n--) {
std::string hobby;
if (getline(is, hobby))
into.hobbies.insert(hobby);
else
is.setstate(std::ios::failbit);
}
}
return is;
}
};
#include <iostream>
int main() {
std::ifstream ifs("input.txt");
Person p;
if (ifs >> p) {
std::cout << "My information\n";
std::cout << p.name << "\n";
std::cout << p.nationality << "\n";
std::cout << "I have " << p.hobbies.size() << " hobbies:\n";
size_t counter = 0;
for(auto const& hobby : p.hobbies) {
std::cout << ++counter << ". " << hobby << "\n";
}
} else {
std::cerr << "Parse failure\n";
}
}

Vector of any type from given struct

Is there any way to create a vector of any type of given structures?
struct STUDENCI
{
int indeks;
string imie;
string nazwisko;
};
struct PRZEDMIOTY
{
int id;
string nazwa;
int semestr;
};
struct SALE
{
string nazwa;
int rozmiar;
bool projektor;
double powierzchnia;
};
vector<ANY TYPE FROM STUDENCI, PRZEDMIOTY, SALE> TAB[3];
You can use a the variant library from boost (www.boost.org):
std::vector<boost::variant<STUDENCI, PRZEDMIOTY, SALE> > v;
E.g. Live on Coliru
#include <boost/variant.hpp>
#include <iostream>
#include <string>
#include <vector>
using std::string;
struct STUDENCI
{
int indeks;
string imie;
string nazwisko;
friend std::ostream& operator << (std::ostream& os, STUDENCI const& v) {
return os << "STUDENCI { " << v.indeks << ", " << v.imie << ", " << v.nazwisko << " }";
}
};
struct PRZEDMIOTY
{
int id;
string nazwa;
int semestr;
friend std::ostream& operator << (std::ostream& os, PRZEDMIOTY const& v) {
return os << "PRZEDMIOTY { " << v.id << ", " << v.nazwa << ", " << v.semestr << " }";
}
};
struct SALE
{
string nazwa;
int rozmiar;
bool projektor;
double powierzchnia;
friend std::ostream& operator << (std::ostream& os, SALE const& v) {
return os << "SALE { " << v.nazwa << ", " << v.rozmiar << ", "
<< std::boolalpha << v.projektor << ", " << v.powierzchnia << " }";
}
};
typedef std::vector<boost::variant<STUDENCI, PRZEDMIOTY, SALE> > Vector;
int main()
{
Vector v;
v.push_back(STUDENCI { 1, "imie", "nazwisko" });
v.push_back(PRZEDMIOTY { 1, "eng101", 3 });
v.push_back(SALE { "auditorium", 42, true, 250 });
for (auto& element: v)
std::cout << element << "\n";
}
Prints
STUDENCI { 1, imie, nazwisko }
PRZEDMIOTY { 1, eng101, 3 }
SALE { auditorium, 42, true, 250 }
That's what unions are for, see the reference for more information on the topic:
Union declaration

Trying to compile and receiving the following errors, undefined references to certain classes.

These are the errors that have occured when trying to compile the file main.cpp:
C:\Users\student\Desktop\C++ Solution Framework (1)\AssignmentSolution\AssignmentSolution\main.o:main.cpp|| undefined reference to `MsgPacket::MsgPacket(int, int, int, int, std::string)'|
C:\Users\student\Desktop\C++ Solution Framework (1)\Assignment Solution\AssignmentSolution\main.o:main.cpp|| undefined reference to `DataStream::DataStream()'|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 1 seconds) ===|
This is the main.cpp file itself:
#include <iostream>
#include <iomanip>
#include "DataStream.h"
#include "MsgPacket.h"
using namespace std;
DataStream * Packet = new DataStream();
DataStream::DataStream();
int main() {
int source;
int destination;
int type;
int port;
int input;
std::string data;
cout << "My Assignment" << endl;;
MsgPacket * Packet = new MsgPacket(source,destination,type,port,data);
}
This is the MsgPacket.h
#ifndef MSGPACKET_H
#define MSGPACKET_H
#include <string>
#include "PacketAddress.h"
using namespace std;
class MsgPacket : public PacketAddress {
public:
MsgPacket();
MsgPacket (const MsgPacket & rhs);
MsgPacket(string dataIn);
MsgPacket(int source, int destination, int port, int type, std::string data);
MsgPacket(int ,char data);
string toString();
string getData() const {return _data;};
void setData(string inData) {_data = inData;};
string dataOutput();
virtual ~MsgPacket();
virtual MsgPacket * Clone() { return new MsgPacket(*this); }
protected:
string _data;
};
#endif // MSGPACKET_H
And finally this is the MsgPacket.cpp
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include "msgpacket.h"
using namespace std;
MsgPacket::MsgPacket():
PacketAddress(0,0)
{
}
MsgPacket::MsgPacket (const MsgPacket & rhs):
PacketAddress(rhs),
_data(rhs.getData())
{
}
MsgPacket::MsgPacket(string dataIn):
PacketAddress(0,0){
string temp;
temp = dataIn.substr (0,4);
_source = atoi(temp.c_str());
temp = dataIn.substr (5,4);
_dest = atoi(temp.c_str());
temp = dataIn.substr (10,4);
_type = atoi(temp.c_str());
temp = dataIn.substr (15,4);
_port = atoi(temp.c_str());
_data = dataIn.substr (20,dataIn.length());
#ifdef DEBUG
cout << "CREATE PACKET: " << this->toString() << endl;
#endif
}
MsgPacket::MsgPacket(int source, int destination):
PacketAddress(source,destination)
{
}
MsgPacket::MsgPacket(int source, int destination, int port):
PacketAddress(source,destination)
{
_port = port;
}
MsgPacket::MsgPacket(int source, int destination, int type, int port, std::string data):
PacketAddress(source, destination)
{
_source = source;
_dest = destination;
_type = type;
_data = data;
_port = port;
}
string MsgPacket::dataOutput()
{
stringstream output;//create a stringstream
output << setw(4) << setfill('0') << _source << ":" << setw(4) << setfill('0') << _dest << ":" << setw(4) << setfill('0') << _type << ":" << setw(4) << setfill('0') << _port << ":" << _data;
return output.str();
}
string MsgPacket::toString()
{
stringstream output;//create a stringstream
output << "[" << showbase << hex << this << "] S:[" << _source << "] D:[" << _dest << "] P:[" << _type << "] T:[" << _port << "]" << " DATA[" << _data << "]";
return output.str();
}
Undefined reference to means that you're trying to refer to something that cannot be linked. Are you linking your two cpp files together?