Unidentified reference to constructor (c++) [duplicate] - c++

This question already has answers here:
Undefined reference C++
(2 answers)
Closed 9 years ago.
I have done some research and googling on this error for days, as far as I know this is a common problem for many in c++, I still haven't found a clear answer to this error. I've read that linking the files can fix this, but I could find any example codes to do this. I'am so close to finishing this code, all I need to do to call the constructor from the main file (or just make a simple object), but I keep getting this "unidentified reference to NamedStorm::NamedStorm()" error, please help.
MAIN.CPP
#include <iostream>
#include <string>
#include "NamedStorm.h"
using namespace std;
NamedStorm storm[2];
int main(){
// NamedStorm Chris("Chris", 70.0, "T.S.", 990.0);
// storm[0] = Chris;
return 0;
}
NamedStorm.cpp
// CPP => Function definition
#include <string>
#include "NamedStorm.h"
using namespace std;
// Defining static variables
int NamedStorm::stormCount = 0;
// Constructor definition
NamedStorm::NamedStorm(std::string sName, double wSpeed, std::string sCat, double sPress){
stormName = sName;
windSpeed = wSpeed;
stormCategory = sCat;
stormPressure = sPress;
stormCount++;
}
NamedStorm::NamedStorm(std::string sName){
stormName = sName;
stormCount++;
}
NamedStorm::NamedStorm(){
stormName = sName;
stormCount++;
}
// Destructor definition
//NamedStorm::~NamedStorm(){}
// Get (Accessor) function definition
int NamedStorm::getStormCount(){
return stormCount;
}
double NamedStorm::getStormPressure(){
return stormPressure;
}
string NamedStorm::getStormCategory(){
return stormCategory;
}
string NamedStorm::getName(){
return stormName;
}
// Set (Mutator) function definition
void NamedStorm::displayOutput(){}
void NamedStorm::sortByNames(){}
void NamedStorm::getAverageStormPressure(){}
void NamedStorm::getAverageWindSpeed(){}
void NamedStorm::getWindSpeed(){}
NamedStorm.h
#ifndef NAMEDSTORM_H_INCLUDED
#define NAMEDSTORM_H_INCLUDED
// NEVER use using namespce in header, use std instead.
class NamedStorm{
private:
std::string stormName;
std::string stormCategory;
double maxWindSpeed;
double stormPressure;
static int stormCount;
public:
// Constructor
NamedStorm(std::string, double, std::string, double);
NamedStorm(std::string);
NamedStorm();
// Destructor
//~NamedStorm();
// Get functions
int getStormCount();
double getStormPressure();
double getWindSpeed();
std::string getStormCategory();
std::string getName();
// Set functions
static void displayOutput();
static void sortByNames();
static void sortByWindSpeed();
static void getAverageWindSpeed();
static void getAverageStormPressure();
};
#endif // NAMEDSTORM_H_INCLUDED

Why is the definition of the default constructor the same as of the NamedStorm::NamedStorm(std::string) ? I would start from correcting that.

Related

Why am I getting undefined reference errors? [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 2 years ago.
I'm getting undefined reference errors. Can you please figure out why?
Errors:
undefined reference to Breuken::Breuken(int, int)
undefined reference to Breuken::som()
(I'm kinda new in c++ programming. I am currently working on a project now, using header files another source file and main source file.)
Here is my code:
Header File (Breuk.H):
using namespace std;
class Breuken{
Breuken(int, int);
void som();
void setTeller1(int);
void setNoemer1(int);
int getTeller1();
int getNoemer1();
private:
int teller1;
int noemer1;
};
Source File(Breuk.cpp):
#include <iostream>
#include "Breuk.h"
using namespace std;
Breuken::Breuken(int tel1, int noem1)
{
setTeller1(tel1);
setNoemer1(noem1);
}
int Breuken::getTeller1()
{
return teller1;
}
int Breuken::getNoemer1()
{
return noemer1;
}
void Breuken::setTeller1(int tel1)
{
teller1 = tel1;
}
void Breuken::setNoemer1(int noem1)
{
noemer1 = noem1;
}
int Breuken::som()
{
cout<<"Breuken zijn: "<<getTeller1()<<" / "<<getNoemer1()<<endl;
}
main file(main.cpp):
#include <iostream>
#include "Breuk.h"
using namespace std;
int main()
{
Breuken br(1, 2);
br.som();
return 1;
}
If I got this right, you want to use a class, but the only thing you did is declare some functions without actually defining them.
What you need to do is put everything in your header inside a class like that:
class Breuk {
private:
int teller1;
int noemer1;
public:
Breuk(int tel1, int noem1);
void som();
void setTeller1(int tel1);
void setNoemer1(int noem1);
int getTeller1();
int getNoemer1();
};
Also, don't forget to give the variables inside the function head a name!
The .cpp file you need to get the reference to the class right (the part before the ::). It has to be the same name as your class. Also, it's not so great to use setter inside the constructor. It's better to reference the member variables directly (the variables inside the class). In order to do that you need to use "this->variable". "this" will refer to the current class you're in. That means if you write this->teller1 it will refer to the variable teller1 inside the class.
#include <iostream>
#include "Breuk.hpp"
using namespace std;
Breuk::Breuk(int tel1, int noem1)
{
// setTeller1(tel1); theoreticly ok but its better to access
// setNoemer1(noem1); member variables (variables inside a class) directly
this->teller1 = tel1;
this->noemer1 = noem1;
}
int Breuk::getTeller1()
{
return teller1;
}
int Breuk::getNoemer1()
{
return noemer1;
}
void Breuk::setTeller1(int tel1)
{
teller1 = tel1;
}
void Breuk::setNoemer1(int noem1)
{
noemer1 = noem1;
}
void Breuk::som()
{
cout << "Breuken zijn: " << getTeller1() << " / " << getNoemer1() << endl;
}
in the main.cpp you only made a small mistake with the return 0 and the name of the class.
#include "Breuk.hpp"
using namespace std;
int main()
{
Breuk br(1, 2); // make sure u use the same name your class has
br.som();
return 0; // return 0 at the end: it means that the program executed correctly
// return 1 would mean that an error occured
}
Also, I suggest using .hpp files instead of .h files. There is no real difference but it's more common to use .hpp for c++.

initializing a static (non-constant) variable of a class.

I have TestMethods.h
#pragma once
// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
class TestMethods
{
private:
static int nextNodeID;
// I tried the following line instead ...it says the in-class initializer must be constant ... but this is not a constant...it needs to increment.
//static int nextNodeID = 0;
int nodeID;
std::string fnPFRfile; // Name of location data file for this node.
public:
TestMethods();
~TestMethods();
int currentNodeID();
};
// Initialize the nextNodeID
int TestMethods::nextNodeID = 0;
// I tried this down here ... it says the variable is multiply defined.
I have TestMethods.cpp
#include "stdafx.h"
#include "TestMethods.h"
TestMethods::TestMethods()
{
nodeID = nextNodeID;
++nextNodeID;
}
TestMethods::~TestMethods()
{
}
int TestMethods::currentNodeID()
{
return nextNodeID;
}
I've looked at this example here: Unique id of class instance
It looks almost identical to mine. I tried both the top solutions. Neither works for me. Obviously I'm missing something. Can anyone point out what it is?
You need to move the definition of TestMethods::nextNodeID into the cpp file. If you have it in the header file then every file that includes the header will get it defined in them leading to multiple defenitions.
If you have C++17 support you can use the inline keyword to declare the static variable in the class like
class ExampleClass {
private:
inline static int counter = 0;
public:
ExampleClass() {
++counter;
}
};

[C++]Constructor doesn't detect components [duplicate]

This question already has an answer here:
C++ constructor definition differences in the code given below [closed]
(1 answer)
Closed 6 years ago.
I'm beginner in OOP and I have problem with definition of constructor.
headfile.h:
#ifndef RACHUNEK_H_INCLUDED
#define RACHUNEK_H_INCLUDED
#include <string>
class Rachunek
{
std::string surname;
std::string nr_account;
double balance;
public:
Rachunek();
Rachunek(std::string & name,std::string & nr,double s = 0.0);
~Rachunek(){};
void show();
void give(const double m);
void get(const double m);
};
#endif // RACHUNEK_H_INCLUDED
file .cpp:
#include <iostream>
#include <string>
#include "rachunek.h"
using namespace std;
Rachunek::Rachunek() //default
{
surname = "not specified";
nr_account = "0000-0000-0000-0000";
balance = 0.0;
}
Rachunek::Rachunek(string & name, string & nr, double s = 0.0) //mysecond
{
surname = name;
nr_account = nr;
balance = s;
}
the problem is the definition of a constructor. I don't know what is wrong...
the problem is the definition of a constructor. I don't know what is wrong...
You are not allowed to have default values in the definition of the function. Default values are allowed only in the declaration. Use:
Rachunek::Rachunek(string & name, string & nr, double s) :
surname(name),
nr_account(nr),
balance(s)
{
}
I suggest changing the implementation of the other constructor to initialize the member variables using initializer list syntax.
Rachunek::Rachunek() :
surname("not specified"),
nr_account("0000-0000-0000-0000"),
balance(0.0)
{
}
If you are able to use a C++11 compiler that can be further simplified by using a delegating constructor.
Rachunek::Rachunek() : Rachunek("not specified", "0000-0000-0000-0000", 0.0)
{
}

How can I call the data type from the function of a class

I defined a class as well as member function. And now I would like to call the data type(x.dat) imported from outside.
How could I do that?
It would be something like this:
class abs{
private:
...
public:
...
void function(data){ //here i would like to use the external data x.dat
...
}
}
Yes, Keith is correct.
What you want is a static variable that maintains the same data across all objects of that type. You don't necessarily need a function to do this.
#include <iostream>
#include <string>
using namespace std;
class abs
{
private:
public:
static double data[3];
};
double abs::data[3]={}; //instantiate the variable
int main () {
abs::data[0]=5.0;
cout<<abs::data[0]; //outputs 5
}
Static variables are associated with the class definition, and not the instantiated objects of that type so as long as the program is active it will be stored in memory as part of the class.
Firstly, tremendous thanks to all of you, especially #Mir
I get it running now, although I don't know why does someone give me a negative!?
I would like to make a summary here, for myself, and future readers.
My question is this:
I have a stored data(double[1000]), which is a file of 'x.dat';
And I define a class 'abs' in the header file, as well as its member function 'function';
And 'function' would like to call data as a inputting parameter.
How to do these?
With the help of Mir, it's working now like this, hope it would help someone:
1.abs.h
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class abs
{
private:
public:
static double data[1000];
double function(double xa[]){
for(int i=0;i<1000;i++){
res += xa[i] * 2.0;
}
return res;
}
};
2.abs.cpp
#include "abs.h"
double abs::data[1000]={}; //instantiate the variable
3.main.cpp
#include "abs.h"
int main () {
abs a = abs();
for(int i = 0; i < 1000, i++){
ifstream fs("x.dat")
fs >> abs::data[i];
cout << abs::data[i]; //outputs all data
}
double Value = a.function(data);
cout<< Value<<endl;
}

Calling a method from a constructor in another class c++

I need to call a method from one class in the constructor of another class. I am not sure how to do this without getting a "was not declared in this scope" error. Note I am just learning C++.
See the comments in symboltable.cpp for what I am trying to accomplish here. I am not looking for anyone to do it for me. I could use an example or pointed in the right direction so I can figure this out.
symboltable.h code:
class SymbolTable
{
public:
SymbolTable() {}
void insert(string variable, double value);
void insert(string variable); // added for additional insert method
double lookUp(string variable) const;
void init(); // Added as mentioned in the conference area.
private:
struct Symbol
{
Symbol(string variable, double value)
{
this->variable = variable;
this->value = value;
}
string variable;
double value;
};
vector<Symbol> elements;
};
symboltable.cpp code:
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
#include "symboltable.h"
/* Implementing the "unreferenced variable" warning.
* Modify the symbol table by adding another insert method
* that supplies only the variable name.
* This method should be called when the variable name
* is encountered while building the arithmetic expression tree.
* It would be called in the constructor of the Variable class.
* The existing insert method, which is called when an assignment is encountered,
* would first check to see whether it is already in the symbol table.
* If it is not, then it is unreferenced.
*/
void SymbolTable::insert(string variable, double value)
{
/* This existing insert method, which is called when an assignment is encountered,
* first needs to check to see whether it is already in the symbol table.
* If it is not, then it is unreferenced.
* */
//Need to check if variable is in the expression need to find out how the expression is stored!
if (find(elements.begin(), elements.end(), variable)) {
const Symbol& symbol = Symbol(variable, value);
elements.push_back(symbol);
} else
throw string("Error: Test for output");
}
/* Adding another insert method that supplies only the variable name.
* This method should be called when the variable name is encountered
* while building the arithmetic expression tree.
* It should be called in the constructor of the Variable class.
*/
void SymbolTable::insert(string variable)
{
const Symbol& symbol = Symbol(variable, symbolTable.lookUp(variable));
elements.push_back(symbol);
}
double SymbolTable::lookUp(string variable) const
{
for (int i = 0; i < elements.size(); i++)
if (elements[i].variable == variable)
return elements[i].value;
else
throw "Error: Uninitialized Variable " + variable;
return -1;
}
void SymbolTable::init() {
elements.clear(); // Clears the map, removes all elements.
}
variable.h code:
class Variable: public Operand
{
public:
Variable(string name) //constructor
{
// how do i call symbolTable.insert(name); here
// without getting 'symboleTable' was not declared in this scope error
this->name = name;
}
double evaluate();
private:
string name;
};
variable.cpp code:
#include <string>
#include <strstream>
#include <vector>
using namespace std;
#include "expression.h"
#include "operand.h"
#include "variable.h"
#include "symboltable.h"
extern SymbolTable symbolTable;
double Variable::evaluate() {
return symbolTable.lookUp(name);
}
There are two solutions:
You use a global variable - like your Variable::evaluate() example. You can of course add your Variable::Variable() as a function in "variable.cpp" instead of the header. Or you can just put a extern SymbolTable symbolTable to the file "variable.h".
You pass in a reference to symbolTable into the constructor (and perhaps store that inside the Variable object - that way, symbolTable doesn't need to be a global variable at all.
By the way, it's generally considered bad style to add using namespace std before header files.
extern SymbolTable symbolTable; needs to go into the header file that is included by everyone who needs symbolTable. Then, in variable.cpp, you need to have SymbolTable symbolTable;
You need to instantiate the second class, either within the constructor, which will make it and its members available only within the constructor of the first class, or in the global namespace. For example:
MyFooClass CFoo;
MyBarClass CBar;
MyFooClass::MyFooClass()
{
CBar = new MyBarClass();
CBar.BarClassMemberFunction();
}