unable to access static methods (C++) - c++

Here's the code:
#include <iostream>
using namespace std;
class Zaix
{
private:
static int mor;
public:
static int beri;
static void setmor(int lip)
{
Zaix::mor=lip;
}
static int getmor(void)
{
return mor;
}
};
int Zaix::beri=3;
int main()
{
cout<<Zaix::beri<<endl;
Zaix::beri++;
cout<<Zaix::beri<<endl;
Zaix::setmor(6);
return 0;
}
Now, line 4 of main() function Zaix::setmor(6); somehow invalidates line 11 of the code presented Zaix::mor=lip;. With this line commented out, the whole thing compiles OK, with it present, compiler gives this error:
undefined reference to Zaix::mor"
Any idea why that is?

Define the variable outside class as well.
int Zaix::mor;
For assignment:
int Zaix::mor = 4;

In C++ we need to define all the static member variable of a class outside of it else we get a linking error. You just need to do like below:-
int Zaix::mor;// Just add this line below int Zaix::beri = 3;

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;
}
};

Can't call a static method in Qt

I have a simple class containing a static attribute. There are two static methods in this class: one to get the static attribute and the other to initialize it. Yet when call the static method the compiler reports an error.
The class:
class Sudoku {
Cell Grid[9][9];
int CurrentLine;
int CurrentColumn;
void deleteValInColumn(int val, int col);
void deleteValInRow(int val, int row);
void deleteValInBox(int val, int x, int y);
static int unsetted; //!
public:
static void IniUnsetted() { //!
unsetted = 0;
}
static int GetUns() { //!
return unsetted;
}
Sudoku(ini InitGrid[9][9]);
void Calculate_Prob_Values();
Cell getCell(int x, int y);
QVector<int> getPossibleValues(int x, int y);
bool SolveIt();
};
This is the error I get:
In member function 'bool Sudoku::SolveIt()':
no return statement in function returning non-void [-Wreturn-type]
In function `ZN6Sudoku6GetUnsEv':
undefined reference to `Sudoku::unsetted` error: ld returned 1 exit status
You will need to define the static variable, even if it is not initialized explicitly. That is what is missing in your code. You should have provided a simple example to reproduce the issue, but for your convenience I am providing one which works.
main.cpp
class Foo {
public:
static int si;
static void bar();
};
int Foo::si = 0; // By default, it will be initialized to zero though.
void Foo::bar() {
Foo::si = 10;
};
int main()
{
Foo::bar();
return 0;
}
Note: I would suggest to get someone to review your code because "unsetted" is incorrect English. If we are at it, you would probably need to fix your indentation as well.
In your code there is no definition of unsetted, there is only declaration.
The solution is to put somewhere in your cpp file a line like this:
int Sudoku::unsetted
The reason for that is that each instantiation of Sudoku class will use the same unsetted member so it cannot be defined for each of them, so it's up to programmer to define it in one place only.
In your cpp file, define the static variable (ideally with an initialization):
int Sudoku::unsetted = 0;
If you are declaring any static variable in class, then you should define that variable outside the class also.
Example:
class A
{
public:
static int x; // declaration
};
int A::x; // definition

C++ static functions and variables

I have written a class as shown below:
#include<iostream>
using namespace std;
class A
{
static int cnt;
static void inc()
{
cnt++;
}
int a;
public:
A(){ inc(); }
};
int main()
{
A d;
return 0;
}
I want to call the function inc through the constructor, but when i compile i am getting an error as:
/tmp/ccWR1moH.o: In function `A::inc()':
s.cpp:(.text._ZN1A3incEv[A::inc()]+0x6): undefined reference to `A::cnt'
s.cpp:(.text._ZN1A3incEv[A::inc()]+0xf): undefined reference to `A::cnt'
I am unable to understand what the error is... plz help...
Static field is not defined - Take a look at Why are classes with static data members getting linker errors?.
#include<iostream>
using namespace std;
class A
{
static int cnt;
static void inc(){
cnt++;
}
int a;
public:
A(){ inc(); }
};
int A::cnt; //<---- HERE
int main()
{
A d;
return 0;
}
Inside the class static int cnt; is only declared, and need to be defined. In C++ you usually declare in your .h .hpp files and then define your static class members in your .c and .cpp files.
In your case, you need to add
int A::cnt=0; // = 0 Would be better, otherwise you're accessing an uninitialized variable.

Pointer to static member variable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++: undefined reference to static class member
The following C++ code compiles well (using g++ -c) but it doesn't link giving the error: undefined reference toAbc::X'`
#include <iostream>
using namespace std;
class Abc {
public:
const static int X = 99;
};
int main()
{
Abc a1;
cout << &(Abc::X) << endl;
}
I want to know why this is not allowed?
You need to have that static member actually defined, not just declared...
Add this line before your main():
const int Abc::X = 99;
As of C++17 you can also do an inline static, in which case the above additional line of code in a .cpp file is not needed:
class Abc {
public:
inline const static int X = 99; // <-- "inline"
};
If the static member is used in a way which requires an lvalue (i.e. in a way that requires it to have an address) then it must have a definition. See the explanation at the GCC wiki, which includes references to the standard and how to fix it.
If you don't like to think about translation units, static initialization order and stuff like that, just change your static constants into methods.
#include <iostream>
using namespace std;
class Abc {
public:
inline static const int& X(){
static int x=99;
return x;
}
};
int main()
{
// Abc a1;
cout << &(Abc::X()) << endl;
}