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
Related
I'm making a heap class to be importable with heap.h and my constructors including bool types do not work, yet every other constructor and function imported works.
Here is what's in heap.h:
#ifndef __HEAP_INCLUDED__
#define __HEAP_INCLUDED__
#include <iostream>
#include <vector>
using namespace std;
class heap{
int capacity;
bool isMinHeap; //1 is min heap -- ascending order
vector<int> * content;
public:
heap();
heap(bool t);
heap(vector<int> * input);
heap(vector<int> * input, bool t);
void print();
void prettyPrint();
int parent(int i);
int leftChild(int i);
int rightChild(int i);
int size();
int getMax();
void insert(int data);
void heapifyDown(int index);
void heapifyUp(int index);
int invalidChild(int index);
int deleteMax();
int deleteMin();
bool minDir();
int at(int index);
};
vector<int> * heapSort(vector<int> * input);
void swap(vector<int> * vec, int a, int b);
#endif
Here are the defined constructors in heap.cpp. Note, all constructors work fine when I add a main to this file to test stuff:
class heap{
vector<int> * content;
int capacity = 256;
bool isMinHeap; //1 is min heap -- ascending order
public:
heap(){
content = new vector<int>;
isMinHeap = 0;
}
heap(bool t){
content = new vector<int>;
isMinHeap = t;
}
heap(vector<int> * input){
content = input;
isMinHeap = true;
for(int i = content->size()/2; i >= 0; i--){
heapifyDown(i);
}
}
heap(vector<int> * input, bool t){
content = input;
isMinHeap = t;
for(int i = content->size()/2; i >= 0; i--){
heapifyDown(i);
}
}
//other functions below
}
The constructors with bool do not work in main.cpp, which has #include "heap.h" at the top. The files are all in the same directory and I am compiling with this command: g++ heap.cpp main.cpp -o main. Why do two of my constructors not work?
The error I see is
/usr/bin/ld: /tmp/ccwomODk.o: in function `main':
main.cpp:(.text+0x4e2): undefined reference to `heap::heap(bool)'
collect2: error: ld returned 1 exit status
-Wall does not elaborate on the issue. I'm pretty sure the issue is with my linking somewhere because the constructors work inside of heap.cpp when I use them in there.
What you are doing with the class in the .cpp file is wrong. You are not allowed to define the class twice. There must only be one class heap { /*...*/ }; in the program (but it may be included in multiple .cpp files). Otherwise the one-definition-rule (ODR) is violated and the program has undefined behavior.
So remove everything you are showing from heap.cpp.
To define the constructors of heap in the heap.cpp file, you need to use this syntax:
#include "heap.h"
heap::heap() {
/*...*/
}
heap::heap(bool t) {
/*...*/
}
//...
and so on. The other member functions must be defined in a similar way, e.g.:
void heap::print() {
/*...*/
}
Furthermore, if you want to have a default member initializer as in
int capacity = 256;
add it in the declaration in the .h file instead.
I also want to add that having a pointer-to-std::vector as member is almost surely a wrong approach as well, but out-of-scope for the question.
When you declare a program element such as a class, function, or
variable, its name can only be "seen" and used in certain parts of
your program. The context in which a name is visible is called its
scope. For example, if you declare a variable x within a function, x
is only visible within that function body.
It seems you broke ODR rule so bad. Your class members including constructors has no body declared in the source file(heap.cpp).
Use '::' to make class members have a body:
//heap.cpp
"heap.h"
heap::heap()
{
}
heap:heap(vector<int> * input, bool t)
{
}
int heap::parent(int i)
{
return i;
}
// this is how you create a body for function that are class members
// the same should be done for all other functions
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;
I want to create a constant static int variable to specify the range of an array. I'm running into problems and getting errors saying that the variable is not a member of the class, but I can print out the variable in main using ClassName::staticVarName.
I cannot figure out how to properly set up a static variable that belongs to a class so that it can be used to initialize an array. The variable prints in main, but for some reason it will not compile when I try to use it to define a classes's array field's range.
error: class "RisingSunPuzzle" has no member "rows"
error: class "RisingSunPuzzle" has no member "cols"
header file for class:
#pragma once
#include<map>
#include<string>
#include<memory>
class RisingSunPuzzle
{
private:
bool board[RisingSunPuzzle::rows][RisingSunPuzzle::cols];
public:
RisingSunPuzzle();
~RisingSunPuzzle();
static const int cols;
static const int rows;
void solvePuzzle();
void clearboard();
};
cpp file for class:
#include "RisingSunPuzzle.h"
const int RisingSunPuzzle::cols = 5;
const int RisingSunPuzzle::rows = 4;
RisingSunPuzzle::RisingSunPuzzle()
{
}
RisingSunPuzzle::~RisingSunPuzzle()
{
}
void RisingSunPuzzle::solvePuzzle()
{
}
void RisingSunPuzzle::clearboard()
{
}
The names of data members that are referred to must be declared before the data members that refer them to.
Also the static constants have to be initializes.
You can reformat the class the following way
class RisingSunPuzzle
{
public:
static const int cols = 5;
static const int rows = 4;
private:
bool board[RisingSunPuzzle::rows][RisingSunPuzzle::cols];
public:
RisingSunPuzzle();
~RisingSunPuzzle();
void solvePuzzle();
void clearboard();
};
//...
There is no need to define the constants if they are not ODR used. Nevertheless you can define them (without initializers) like
const int RisingSunPuzzle::cols;
const int RisingSunPuzzle::rows;
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.
I am starting to learn C++ and Qt, but sometimes the simplest code that I paste from a book results in errors.
I'm using g++4.4.2 on Ubuntu 10.04 with QtCreator IDE. Is there a difference between the g++ compiler syntax and other compilers? For example when I try to access static members something always goes wrong.
#include <iostream>
using namespace std;
class A
{
public:
static int x;
static int getX() {return x;}
};
int main()
{
int A::x = 100; // error: invalid use of qualified-name 'A::x'
cout<<A::getX(); // error: : undefined reference to 'A::x'
return 0;
}
I think it's exactly the same as declared here and here (isn't it?). So what's wrong with the above code?
You've declared the static members fine, but not defined them anywhere.
Basically what you've said "there exists some static member", but never set aside some memory for it, you need:
int A::x = 100;
Somewhere outside the class and not inside main.
Section [9.4.2]
Static Data Members
The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator
You need to define the static member variable of the class outside the class as static member variables require declaration as well as definition.
#include <iostream>
using namespace std;
class A
{
public:
static int x;
static int getX() {return x;}
};
int A::x; // STATIC MEMBER VARIABLE x DEFINITION
int main()
{
A::x = 100; // REMOVE int FROM HERE
cout<<A::getX();
return 0;
}
Try:
#include <iostream>
using namespace std;
class A
{
public:
// This declares it.
static int x;
static int getX(){return x;}
};
// Now you need an create the object so
// This must be done in once source file (at file scope level)
int A::x = 100;
int main()
{
A::x = 200;
// Notice no 'int' keyword before A::x on this line. You can modify A::x
cout<<A::getX(); // Should work
return 0;
}
The definition of static member variables must live at file scope, i.e. outside all functions, etc.
Try this example:
#include<iostream>
using namespace std;
class check
{
static int a;
public:
void change();
} ;
int check::a=10;
void check::change()
{
a++;
cout<<a<<"\n";
}
int main()
{
int i,j;
check c;
check b;
c.change();
b.change();
return 0;
}
Now you have worked out how to use static class members I will advise you that you should generally use them only in the following circumstances:
For use in templates. So in your example you could have GetX() in different classes and in a template somewhere you would use
template< typename T >
int func()
{
return T::GetX();
}
although obviously more elaborate. But here your static function being in a class serves a purpose.
Where the function needs access to the class, i.e. to private members. You could make it a friend but you may as well make it static. Often the case in callbacks.
The rest of the time you can probably use compilation-unit level functions and variables which has the advantage of taking your members out of the header (particularly if they are private). The less implementation detail you give the better.
You can use the inline keyword since c++ 17 in front of static members to avoid a definition outside of class scope. Your code should now look like this:
#include <iostream>
using namespace std;
class A
{
public:
inline static int x;
static int getX() {return x;}
};
int main()
{
A::x = 100; //Works now
cout<<A::getX()<<'\n';
return 0;
}
Case 1: static variable
As we all know, defining a static variable inside a class which will throw compilation error. E.g. below
class Stats
{
public:
static int AtkStats[3];
*static int a =20;* // Error: defining a value for static variable
};
int Stats::AtkStats[3] = {10, 0, 0};
Output:
error: ISO C++ forbids in-class initialization of non-const static member 'Stats::a'
Case 2: const static variable
For const static variable, we can define a value either inside a class or Outside class.
class Stats
{
public:
static const int AtkStats[3];
static const int a =20; // Success: defining a value for a const static
};
const int Stats::AtkStats[3] = {10, 0, 0};
const int Stats::a = 20; // we can define outside also
Output:
Compilation success.