C++ Access private static member from public static method? [duplicate] - c++

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 9 years ago.
Let's say I have a .hpp file containing a simple class with a public static method and a private static member/variable.
This is an example class:
class MyClass
{
public:
static int DoSomethingWithTheVar()
{
TheVar = 10;
return TheVar;
}
private:
static int TheVar;
}
And when I call:
int Result = MyClass::DoSomethingWithTheVar();
I would expect that "Result" is equal to 10;
Instead I get (at line 10):
undefined reference to `MyClass::TheVar'
Line 10 is "TheVar = 10;" from the method.
My question is if its possible to access a private static member (TheVar) from a static method (DoSomethingWithTheVar)?

The response to your question is yes ! You just missed to define the static member TheVar :
int MyClass::TheVar = 0;
In a cpp file.
It is to respect the One definition rule.
Example :
// Myclass.h
class MyClass
{
public:
static int DoSomethingWithTheVar()
{
TheVar = 10;
return TheVar;
}
private:
static int TheVar;
};
// Myclass.cpp
#include "Myclass.h"
int MyClass::TheVar = 0;

Related

private: static class member initialization with inclass setter called by method in different class returns error - unresolved symbols [duplicate]

This question already has answers here:
Undefined reference to static class member
(9 answers)
Closed 7 months ago.
This post was edited and submitted for review 3 months ago and failed to reopen the post:
Original close reason(s) were not resolved
The question is a duplicate in concept, but the error is articulated differently. Unresolved symbols should be understood as undefined reference. If you are new to C++, please take the time to read the errors generated by my code.
I am taking a course in C++ and OOP, and I need some help understanding what I am doing wrong and what I can do to correct it.
I have a code skeleton, where I cannot change class members by changing them from static to non-static. In my current hand-out, I need to create an object of the first class in a second class, and call a method in the first class. I cannot move class members from private to public or public to private, and I cannot change them from static to non-static.
My goal is to write methods in the second class that uses the setters and getters from the first class, using an object in the second class, and to call the methods in the second class in int main().
Here is a basic idea of what I have written in attempting what I described.
#include <iostream>
using namespace std;
class foo
{
private:
static string goo;
static long int doo;
public:
static void setGoo(string gooString)
{
goo = gooString;
}
static void setDoo(long int dooLongInt)
{
doo = dooLongInt;
}
static string getGoo()
{
return goo;
}
static long int getDoo()
{
return doo;
}
};
class moo
{
private:
foo fooObj;
public:
void setGoo(string gooString)
{
fooObj.setGoo(gooString);
}
void setDoo(long int dooLongInt)
{
fooObj.setDoo(dooLongInt);
}
string getGoo()
{
return fooObj.getGoo();
}
long int getDoo()
{
return fooObj.getDoo();
}
};
int main()
{
moo mainMoo;
string text = "Text";
mainMoo.setGoo(text);
mainMoo.setDoo(123);
cout << mainMoo.getGoo();
cout << mainMoo.getDoo();
return 0;
};
I get these errors when I compile it.
1>Source.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > foo::goo" (?goo#foo##0V?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##A)
1>Source.obj : error LNK2001: unresolved external symbol "private: static long foo::doo" (?doo#foo##0JA)
1>C:\Users\ipyra\OneDrive\Documents\edx hands-on projects\Static class private member initialization\x64\Debug\Static class private member initialization.exe : fatal error LNK1120: 2 unresolved externals
Class static members need to initialize outside a class, that is the reason of link error.
class foo
{
private:
static string goo;
static long int doo;
public:
// .... other code
};
string foo::goo = "";
long int foo::doo = 0;
Use inline keyword in C++ 17, we can defined static member inside class.
http://en.cppreference.com/w/cpp/language/static
Another similar question
How to initialize private static members in C++?

How to define a static member struct in C++ [duplicate]

This question already has answers here:
Undefined reference to static class member
(9 answers)
how to initialize and use static struct [duplicate]
(2 answers)
Closed 2 years ago.
I have a class that has a static member struct
class SharedMem
{
public:
struct memory {
char buff[100];
int status, pid1, pid2;
};
static struct memory* shmptr;
}
I would like to define the static struct using
SharedMem::memory shmptr;
But I'm getting errors undefined reference to 'SharedMem::shmptr'
How do I properly define the struct in C++?
And follow up question, how can I define this struct if my class is entirely in the header file, can I define it after the class declaration at the bottom of the header file?
Thanks
class SharedMem
{
public:
struct memory {
char buff[100];
int status, pid1, pid2;
};
static memory* shmptr;
};
// must add this in the cpp file!
SharedMem::memory* SharedMem::shmptr = nullptr;

Member variable pointer to self in C++ [duplicate]

This question already has answers here:
Undefined reference to static class member
(9 answers)
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 8 years ago.
When I try to compile this code, why does g++ report an error?
class A {
private:
static A* Aptr[5];
public:
static int A_count;
A() {
Aptr[A_count] = this;
}
};
int A::A_count = 0;
int main() {
A a_;
A b_;
return 0;
}
/tmp/ccrp4BGg.o: In function `A::A()':
try.cpp:(.text._ZN1AC2Ev[_ZN1AC5Ev]+0x18): undefined reference to `A::Aptr'
collect2: error: ld returned 1 exit status
Explanation
You have only declared your static data-member named A::Aptr, but in order to use it, as you are inside the constructor of A, you must provide a definition.
The linker diagnostic might say undefined reference, which might be hard to relate to a missing definition, but it's talking about its internal mapping of names and storage location.
In other words; the linker is unable to find a a reference (ie. entry) for the location where A::Aptr is stored, which makes sense: Without a definition you haven't given A::APtr any storage to use.
Solution
You've already provided both a declaration (2), and a definition (4) for A::A_count, if you do the same for A::APtr you will be all set.
class A {
private:
static A* Aptr[5]; // (1), declaration
public:
static int A_count; // (2), declaration
A() {
Aptr[A_count] = this;
}
};
A* A::APtr[5]; // (3), definition <-- previously missing!
int A::A_count = 0; // (4), definition
Note: You are only asking about the linker error, but I'm guessing you mean to increment A_count upon constructing an object of type A, something which you are currently not doing.
You need to define it outside the class, just like any other static variable:
Because it is static you need to define Aptr outside of the class, right now you have only declared it but not defined and initialized it. This means that the linker can't find it. Also do you want to increment A_count?:
class A {
private:
static A* Aptr[5];
public:
static int A_count;
A() {
Aptr[A_count] = this;
A_count++; //I presume you want to do something like this too
}
};
int A::A_count = 0;
A* A::Aptr[5] = { nullptr }
int main() {
A a_;
A b_;
return 0;
}
class A {
private:
static A* Aptr[5];
public:
static int A_count;
A() {
Aptr[A_count] = this;
}
//static ctor
static A(){
Aptr=new A[5];
A_count=0;
}
};
int main() {
A a_;
A b_;
return 0;
}

unresolved external symbol when static variable is defined inside the class declaration [duplicate]

This question already has answers here:
Should a const static variable be initialized in a c++ header file?
(4 answers)
Closed 9 years ago.
I am going to get right to the point:
//ComponentHolder.h
template<class Holder, uint ID>
class TemplateComponentHolder : public ComponentHolderInterface {
protected:
std::vector<ComponentType*> mComponents;
public:
TemplateComponentHolder() : ComponentHolderInterface(ID) {}
static const uint getStaticID() { return ID; }
};
class ConcereteComponentHolder1 : public TemplateClassHolder<ComponentType, 1000> {
public:
inline void print() { std::cout << "test"; }
};
//World.h
class World {
private:
std::map<uint, ComponentHolderInterface*> mHolders;
public:
template<class Holder> Holder * getHolder() {
auto i = mHolders.find(Holder::getStaticID());
if(i != mHolders.end())
return static_cast<Holder*>((*i));
return NULL;
}
/* ... */
};
//Main code
int main() {
World * world = new World;
world->addHolder(new ConcerteComponentHolder1);
world->getHolder<ConcreteComponentHolder1>()->print();
}
I get unresolved external symbol error. Says cannot resolve "ConcereteComponentHolder1::ID". If I change the static variable to non const and add it to a source file:
//ComponentHolder.cpp
uint ConcreteComponentHolder1::ID = 1000;
There is no problem. It makes sense why the latter one must be defined explicitly. But when I am using const, I have to define it in the header. Getting a linker error when using const just doesn't make sense. Is it because of the template function being generated in the header? Or is it something else?
Placing a variable declaration together with an initialiser in the class declaration dies not actually constitute a definition. You can get away without the definition as long as you only ever take it's value and never try to use it as a reference.
'find' takes a reference to the value as an argument. This means you need an actual variable defined somewhere to take a reference to it.
You might also like to read this SO question: Defining static const integer members in class definition

Can't return instannce of a class Foo from it static method [duplicate]

This question already has answers here:
Defining private static class member
(6 answers)
Closed 9 years ago.
I want to return first created instannce of a class Foo(there will be really one instance created during all program life-cycle) from it static method. Here sample code:
//.h
#pragma once
class Foo
{
static Foo* _firstInstance;
public:
Foo();
~Foo();
static Foo* GetFirstFoo();
};
//.cpp
#include "stdafx.h"
#include "Foo.h"
Foo::Foo()
{
_firstInstance = this;
}
Foo::~Foo()
{
}
Foo* Foo::GetFirstFoo()
{
return _firstInstance;
}
But i got next error:
Error 1 error LNK2001: unresolved external symbol "private: static class Foo * Foo::_firstInstance" (?_firstInstance#Foo##0PAV1#A) c:\Users\Brans\documents\visual studio 2013\Projects\testSt\testSt\Foo.obj testSt
What is wrong? I am new in c++ but i remember that i created class instance constructor from static method without problems.
Static member must be also defined in a .cpp file:
Foo* Foo::_firstInstance;