Compiling class issue - c++

Keep getting these errors while trying to compile an c++ class program.
testStock.cpp: In function ‘int main()’: testStock.cpp:8: error:
‘Stock’ was not declared in this scope testStock.cpp:8: error:
expected ;' before ‘first’ testStock.cpp:9: error: ‘first’ was not
declared in this scope testStock.cpp:12: error: expected;' before
‘second’ testStock.cpp:13: error: ‘second’ was not declared in this
scope
stock.h
#ifndef STOCK_H
#define STOCK_H
using namespace std;
class Stock
{
private:
string symbol;
string name;
double previousClosingPrice;
double currentPrice;
public:
Stock(string symbol, string name);
string getSymbol() const;
string getName() const;
double getPreviousClosingPrice() const;
double getCurrentPrice() const;
double changePercent();
void setPreviousClosingPrice(double);
void setCurrentPrice(double);
};
#endif
stock.cpp
#include <string>
#include "stock.h"
Stock::Stock(string symbol, string name)
{
this->symbol = symbol;
this->name = name;
}
string Stock::getSymbol() const
{
return symbol;
}
string Stock::getName() const
{
return name;
}
void Stock::setPreviousClosingPrice(double closing)
{
previousClosingPrice = closing;
}
void Stock::setCurrentPrice(double current)
{
currentPrice = current;
}
double Stock::getPreviousClosingPrice() const
{
return previousClosingPrice;
}
double Stock::getCurrentPrice() const
{
return currentPrice;
}
double Stock::changePercent()
{
return ((currentPrice - previousClosingPrice)/previousClosingPrice) * 100;
}
testStock.cpp
#include <string>
#include <iostream>
#include "string.h"
using namespace std;
int main()
{
Stock first("aapl", "apple");
cout << "The stock symbol is " << first.getSymbol() << " and the name is " << first.getName() << endl;
first.setPreviousClosingPrice(130.0);
first.setCurrentPrice(145.0);
Stock second("msft", "microsoft");
second.setPreviousClosingPrice(30.0);
second.setCurrentPrice(33.0);
first.changPercent();
second.changePercent();
cout << "The change in percent for " << first.getName << " is " << first.changePercent() << endl;
cout << "The change in percent for " << second.getName << " " << second.getSymbol() << " is " << second.changePercent() << endl;
return 0;
}
Im sure its something obvious but its only my second class program.

It looks like you have omitted
#include "stock.h"
from your testStock.cpp.

Compiler tells you "‘Stock’ was not declared in this scope ". So you should ask yourself "Where is 'Stock' declared?" and you should be able to answer it: "It's declared in stock.h".
And "Why compiler doesn't know that 'Stock' is declared in stock.h?" Because you haven't included it. So as it was mentioned here already, #include "stock.h" is the solution.
Hope you will spend more time reading compilers errors / warnings and also more time trying to understand them ;)

You are just not including "stock.h" in your main file, so the compiler doesn't know what Stock first means.

#include "stock.h"
and you will be able to create Stock object as it will be visible to your TestStock class.

Related

Calling a string getter function from a header file

I'm learning C++, and I'm just messing around with putting classes in separate files for practice. I have a getter function, which returns a string (because the variable is saved as a string). However, from my main() function, I am not sure how to call it. I know the problem is probably that I need to include string somewhere when I call the object, but I have no idea how to format it.
I know this is a pretty newbie questions, but I couldn't find the answer anywhere. Could someone help me out?
(p.s. I'm not trying to get this specific code to work, since it's useless. I'm just trying to learn how to apply it for future reference).
I've tried throwing in string in a couple of places when calling or creating the object, but I always get an error. I know I could get around it by not encapsulating the variable or not having a separate class file, but that's not what I want.
main.cpp
#include <iostream>
#include "usernameclass.h"
#include <string>
using namespace std;
int main()
{
usernameclass usernameobject;
usernameobject.getUsername();
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
usernameclass();
std::string getUsername();
void setUsername(std::string name);
askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include "usernameclass.h"
#include <iostream>
#include "username.h"
#include <string>
using namespace std;
string usernameclass::getUsername(){
return usernameVar;
cout << "test cout" << endl;
}
usernameclass::askUsername(){
string name;
cout << "What is your name?" << endl;
cin >> name;
setUsername(name);
cout << "Ah, so your name is "+usernameVar+", great name I guess!" << endl;
cin.get();
cin.get();
cout << "You're about to do some stuff, so get ready!" << endl;
}
usernameclass::usernameclass(){}
void usernameclass::setUsername(string name){
string* nameptr = &usernameVar;
*nameptr = name;
}
Expected result: runs getUsername() function and returns usernameVar
Actual result: doesn't run the getUsername() function
The current code would not compile, because you have not specified return type of 'askUsername()' routine, which is 'void', I believe.
Other things are good, apart from an output in 'getUsername()', which happens after returning from the function and about which you should have received a warning, I guess.
To the question: you can call that 'get' method in 'main()' as:
cout << usernameobject.getUsername();
Your code should be structured more like this instead:
main.cpp
#include <iostream>
#include "usernameclass.h"
int main()
{
usernameclass usernameobject;
// optional:
// usernameobject.askUsername();
// do something with usernameobject.getUsername() as needed...
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
std::string getUsername() const;
void setUsername(std::string name);
void askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include <iostream>
#include "usernameclass.h"
std::string usernameclass::getUsername() const {
return usernameVar;
}
void usernameclass::setUsername(std::string name) {
usernameVar = name;
}
void usernameclass::askUsername() {
std::string name;
std::cout << "What is your name?" << std::endl;
std::getline(std::cin, std::name);
setUsername(name);
std::cout << "Ah, so your name is " << getUsername() << ", great name I guess!" << std::endl;
std::cout << "You're about to do some stuff, so get ready!" << std::endl;
}

C++ clang linker command failed with exit code 1 [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.
My professor gave me two class header and .cpp files to build on. When I include these in main, they work fine. Whenever I just use his files, I get linker errors with clang and xcode.
Here's the error:
shannigan#mbp-007100 inheritance (master) $ make main
c++ main.cpp -o main
Undefined symbols for architecture x86_64:
"SavitchEmployees::SalariedEmployee::SalariedEmployee()", referenced from:
_main in main-0d7e27.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [main] Error 1
Here's my main:
#include "employee.h"
#include "salariedemployee.h"
#include <string>
#include <cstdlib>
#include <iostream>
using namespace SavitchEmployees;
using namespace std;
int main() {
cout << "Do I run?" << endl;
SalariedEmployee sam;
return 0;
};
The header file for Employee:
//This is the header file employee.h.
//This is the interface for the class Employee.
//This is primarily intended to be used as a base class to derive
//classes for different kinds of employees.
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using std::string;
namespace SavitchEmployees
{
class Employee
{
public:
Employee( );
Employee(const string& theName, const string& theSsn);
string getName( ) const;
string getSsn( ) const;
double getNetPay( ) const;
void setName(const string& newName);
void setSsn(const string& newSsn);
void setNetPay(double newNetPay);
void printCheck( ) const;
protected:
string name;
string ssn;
double netPay;
};
}//SavitchEmployees
#endif //EMPLOYEE_H
The CPP file for main:
//This is the file: employee.cpp
//This is the implementation for the class Employee.
//The interface for the class Employee is in the header file employee.h.
#include <string>
#include <cstdlib>
#include <iostream>
#include "employee.h"
using std::string;
using std::cout;
namespace SavitchEmployees
{
Employee::Employee( ) : name("No name yet"), ssn("No number yet"), netPay(0)
{
//deliberately empty
}
Employee::Employee(const string& theName, const string& theNumber)
: name(theName), ssn(theNumber), netPay(0)
{
//deliberately empty
}
string Employee::getName( ) const
{
return name;
}
string Employee::getSsn( ) const
{
return ssn;
}
double Employee::getNetPay( ) const
{
return netPay;
}
void Employee::setName(const string& newName)
{
name = newName;
}
void Employee::setSsn(const string& newSsn)
{
ssn = newSsn;
}
void Employee::setNetPay (double newNetPay)
{
netPay = newNetPay;
}
void Employee::printCheck( ) const
{
cout << "\nERROR: printCheck FUNCTION CALLED FOR AN \n"
<< "UNDIFFERENTIATED EMPLOYEE. Aborting the program.\n"
<< "Check with the author of the program about this bug.\n";
exit(1);
}
}//SavitchEmployees
SalariedEmployees header:
//This is the header file salariedemployee.h.
//This is the interface for the class SalariedEmployee.
#ifndef SALARIEDEMPLOYEE_H
#define SALARIEDEMPLOYEE_H
#include <string>
#include "employee.h"
using std::string;
namespace SavitchEmployees
{
class SalariedEmployee : public Employee
{
protected:
double salary;//weekly
public:
SalariedEmployee( );
SalariedEmployee (const string& theName, const string& theSsn,
double theWeeklySalary);
double getSalary( ) const;
void setSalary(double newSalary);
void printCheck( );
};
}//SavitchEmployees
#endif //SALARIEDEMPLOYEE_H
SalariedEmployee.cpp:
//This is the file salariedemployee.cpp
//This is the implementation for the class SalariedEmployee.
//The interface for the class SalariedEmployee is in
//the header file salariedemployee.h.
#include <iostream>
#include <string>
#include "salariedemployee.h"
using std::string;
using std::cout;
using std::endl;
namespace SavitchEmployees
{
SalariedEmployee::SalariedEmployee( ) : Employee( ), salary(0)
{
//deliberately empty
}
SalariedEmployee::SalariedEmployee(const string& newName, const string& newNumber,
double newWeeklyPay)
: Employee(newName, newNumber), salary(newWeeklyPay)
{
//deliberately empty
}
double SalariedEmployee::getSalary( ) const
{
return salary;
}
void SalariedEmployee::setSalary(double newSalary)
{
salary = newSalary;
}
void SalariedEmployee::printCheck( )
{
setNetPay(salary);
cout << "\n__________________________________________________\n";
cout << "Pay to the order of " << getName( ) << endl;
cout << "The sum of " << getNetPay( ) << " Dollars\n";
cout << "_________________________________________________\n";
cout << "Check Stub NOT NEGOTIABLE \n";
cout << "Employee Number: " << getSsn( ) << endl;
cout << "Salaried Employee. Regular Pay: "
<< salary << endl;
cout << "_________________________________________________\n";
}
}//SavitchEmployees
How can I get rid of these linker errors so I can focus on my actual code? Is there anything obvious wrong? The only thing I've changed was making the "private" variables protected.
I can't see the class named SalariedEmployee.
I think the main function should look like this.
int main() {
cout << "Do I run?" << endl;
Employee sam;
return 0;
};
You have to use Employee instead of SalariedEmployee

g++ Undefined reference to base class destructor and derived class pointer

Edit: I had forgotten to explicitly define my class destructors in their respective .cpp files. I replaced *p with string *killList = new string[10];
and my code now compiles. Thanks for your replies!
I've tried to compile the following files using the command :
g++ -o hunter hunter_h.h hunter_h.cpp animal_h.h animal_h.cpp main.cpp
animal_h.h
#include <iostream>
#include <string>
#ifndef ANIMAL_H
#define ANIMAL_H
using namespace std;
// Animal class
class animal
{
friend class hunter;
// need a name, species, private ID
public:
animal();
animal(string aSpecies);
string name;
string species;
string getSpecies();
void setName(string aName);
string getName();
int getID();
~animal();
private:
static int uID;
};
#endif
animal_h.cpp
#include "animal_h.h"
//#include "hunter_h.h"
#include <iostream>
#include <string>
using namespace std;
int animal:: uID = 0 ;
animal::animal()
{
cout << "Created an animal!" << endl;
name = "?";
species = "?";
uID++;
}
animal::animal(string aSpecies)
{
cout << "Created 1 "<< aSpecies << "!" << endl;
name= "?";
species = aSpecies;
uID++;
}
string animal::getSpecies()
{
cout << species << endl;
}
void animal::setName(string aName)
{
name = aName;
cout << "This " << species << " is now called " << name << endl;
}
string animal::getName()
{
cout << name << endl;
}
int animal:: getID()
{
cout << uID << endl;
}
hunter_h.h This is a derived class of the animal base class with unique behaviors.
#include "animal_h.h"
#include <iostream>
#ifndef ANIMAL_HUNTER
#define ANIMAL_HUNTER
class hunter : public animal
{
public:
hunter();
hunter(std::string aSpecies);
void recordKills(std::string kill);
static int tKills;
int totalKills();
static std::string *theKills();
static std::string *p;
static int clearTotal();
~hunter();
};
#endif
hunter_h.cpp
#include "animal_h.h"
#include "hunter_h.h"
#include <iostream>
#include <string>
using namespace std;
int hunter:: tKills =0;
string killList[10];
hunter::hunter()
{
cout<<"created a hunter! "<<endl;
name= "? ";
species="? ";
string *p;
p = &killList[0];
}
hunter::hunter(string aSpecies)
{
name = "?";
species = aSpecies;
cout << "created a hunting "<<species <<endl;
}
string *theKills()
{
return hunter::p;
}
void hunter::recordKills(string kill)
{
cout << kill << " killed." << endl;
*(p+tKills) = kill;
tKills++;
cout << tKills << " total kills." << endl;
}
int hunter::totalKills()
{
cout << name << "'s " << "Total kills: " << tKills << endl;
}
int hunter::clearTotal()
{
delete[] killList;
return 0;
}
main.cpp
#include "animal_h.h"
#include "hunter_h.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
hunter *hunterC;
hunterC= new hunter("cheetah");
hunterC->recordKills("Mouse");
hunterC-> recordKills("Gazelle, Gazelle");
hunterC-> recordKills("Hyena");
hunterC-> recordKills("Rabbit, Rabbit");
hunterC->theKills;
hunterC->clearTotal;
}
Now, when I try to compile I get the following warning and errors:
hunter_h.cpp: In static member function ‘static int hunter::clearTotal()’:
hunter_h.cpp:49:11: warning: deleting array ‘killList’
delete[] killList;
^
/tmp/ccnv8xdj.o:hunter_h.cpp:(.text+0x71): undefined reference to `animal::~animal()'
/tmp/ccnv8xdj.o:hunter_h.cpp:(.text+0x101): undefined reference to `animal::~animal()'
/tmp/ccnv8xdj.o:hunter_h.cpp:(.text+0x119): undefined reference to `hunter::p'
/tmp/ccnv8xdj.o:hunter_h.cpp:(.text+0x15a): undefined reference to `hunter::p'
/tmp/ccqCD1e7.o:main.cpp:(.text+0x1f4): undefined reference to `animal::~animal()'
/tmp/ccqCD1e7.o:main.cpp:(.text+0x20c): undefined reference to `animal::~animal()'
collect2: error: ld returned 1 exit status
I've been learning C++ for a couple months only so am not sure where the above code is going wrong. How can I get this to compile and run?
killList is not allocated using new[], then dont delete it with delete[]. It is not allocated runtime, then it does not have to be deallocated explicitly. It will release its memory when the program exits. With your code as it is you are running the chance of overrunning you killList array.
Try using std::vector instead.
std::vector<std::string> killList;
...
void recordKills(std::string s)
{
...
killList.push_back(s);
}
void clearTotal()
{
killList.clear();
}

I can't figure out C++ syntax error "expected `;' before ‘{’ token"

I have this simple code and am getting a syntax error:
file.cc:67: error: expected `;' before ‘{’ token
file.cc:73: error: expected primary-expression before ‘(’ token
file.cc:73: error: expected primary-expression before ‘n’
file.cc:73: error: expected `;' before ‘{’ token
I've put stars around the lines that are 67 and 73, which are the constructors for the class. I'm very new to C++ and can't find the syntax issue. This is the first time I've made a constructor.
int main() {
class Patient {
private: // default is private but stating explicitly here for learning purposes
std::string name; //object
int height; //object
int weight; //object
public:
Patient(); //constructor
Patient(std::string); //constructor
void set_name (std::string n) {name=n;} //fn
void set_height (int h) {if (height>0){height=h;} else {height=0;}} //fn
void set_weight (int w) {if (weight>0){weight=w;} else {weight=0;}} //fn
std::string get_name(){return name;} //fn
int get_height(){return height;} //fn
int get_weight(){return weight;} //fn
int bmi(void) {
if ((height!=0) && (weight!=0))
return (weight/(height*height));
else
return 0;
}
};
Patient::Patient () { // **LINE 67**
name="string";
height=0,
weight=0;
}
Patient::Patient(std::string n) {name=n;height=0;weight=0;} // **LINE 73**
Patient father("Andrew Nonymous");
Patient mother("Ursula N. Known");
Patient baby;
//Father's height and weight are unknown.
mother.set_name("Ursula N. Nonymous");
mother.set_height(1.65);
mother.set_weight(58);
baby.set_height(0.495);
baby.set_weight(3.4);
std::cout << "Baby: " << baby.get_name() << " BMI: " << baby.bmi() << std::endl;
std::cout << "Mother: " << mother.get_name() << " BMI: " << mother.bmi() << std::endl;
std::cout << "Father: " << father.get_name() << " BMI: " << father.bmi() << std::endl;
return 0;
}
If you want to define a class inside a function you have to define every method of that class inline in the class definition. For example:
class Patient {
private: // default is private but stating explicitly here for learning purposes
std::string name; //object
int height; //object
int weight; //object
public:
Patient()
{
name="string";
height=0;
weight=0;
}
};
Since you are new to C++ I'm guessing that while the other answer will get your code to compile you may want to try the more standard way of using class header and implementation files, which will get you used to having reusable classes rather than classes defined within main() (or other functions).
Just move the class declaration into a file called "Patient.h" and move the implementation (definition of the functions) to "Patient.cpp". In both your main file and Patient.cpp, include Patient.h
Here's a Patient.h:
#ifndef Patient_h
#define Patient_h
#include <string>
class Patient {
private: // default is private but stating explicitly here for learning purposes
std::string name; //object
int height; //object
int weight; //object
public:
Patient(); //constructor
Patient(std::string); //constructor
void set_name (std::string n) {name=n;} //fn
void set_height (int h) {if (height>0){height=h;} else {height=0;}} //fn
void set_weight (int w) {if (weight>0){weight=w;} else {weight=0;}} //fn
std::string get_name(){return name;} //fn
int get_height(){return height;} //fn
int get_weight(){return weight;} //fn
int bmi(void) {
if ((height!=0) && (weight!=0))
return (weight/(height*height));
else
return 0;
}
};
#endif
Patient.cpp:
#include "Patient.h"
Patient::Patient () {
name="string";
height=0;
weight=0;
}
Patient::Patient(std::string n) {name=n;height=0;weight=0;}
And what's left in main.cpp:
#include <iostream>
#include "Patient.h
int main() {
Patient father("Andrew Nonymous");
Patient mother("Ursula N. Known");
Patient baby;
//Father's height and weight are unknown.
mother.set_name("Ursula N. Nonymous");
mother.set_height(1.65);
mother.set_weight(58);
baby.set_height(0.495);
baby.set_weight(3.4);
std::cout << "Baby: " << baby.get_name() << " BMI: " << baby.bmi() << std::endl;
std::cout << "Mother: " << mother.get_name() << " BMI: " << mother.bmi() << std::endl;
std::cout << "Father: " << father.get_name() << " BMI: " << father.bmi() << std::endl;
return 0;
}
If you are working in an IDE it will compile both main.cpp and Patient.cpp for you; if you're using g++ or clang at the command line just make sure to include both .cpp files when you compile, e.g.
$ g++ main.cpp Patient.cpp -o myPatientProgram
...then you can run ./myPatientProgram to see your program run.
hth

Linker error undefined reference to class::class (Person::Person in my case)

I am getting a linker error undefined reference to Person::Person when trying to implement my program. The three parts are below. I have been working on fixing it for a few hours now. I know it's probably something simple that I am just not seeing. But I have looked around on the internet and still have not found my answer. So any help would be appreciated.
#ifndef PERSON0_H_
#define PERSON0_H_
#include <string>
class Person // class declaration
{
private:
static const int LIMIT = 25;
std::string lname;
char fname[LIMIT];
public:
Person() {lname = ""; fname[0] = '\0';}
Person(const std::string & ln, const char * fn = "Hay you");
void Show() const;
void FormalShow() const;
};
#endif
#include <iostream>
#include <string>
#include "person0.h"
void Person::Show() const
{
using namespace std;
std::cout << fname << " " << lname << '\n';
}
void Person::FormalShow() const
{
using std::cout;
std::cout << lname << ", " << fname << '\n';
}
#include <iostream>
#include <string>
#include "person0.h"
int main()
{
using namespace std;
Person one;
Person two("Smythecraft");
Person three("Dimwiddy", "Sam");
one.Show();
cout << endl;
one.FormalShow();
cout << endl;
two.Show();
cout << endl;
two.FormalShow();
cout << endl;
three.Show();
cout << endl;
three.FormalShow();
cin.get();
cin.get();
return 0;
}
I am not really a C++ person, so the terminology might be wrong, but I would say that the implementation of the
Person::Person(const std::string & ln, const char * fn)
constructor is missing.