I have switched from c to c++ recently for my project. I am facing difficulty in initializing static pointer.
Here is some what similar code in my project
file1 static.h
#include "static.h"
int shared::a = 2; // define a
int shared::*ptr = NULL;
void shared::show()
{
memcpy(&ptr, &a, sizeof(int));
cout << "This is static a: " << a;
cout << "\nThis is ptr = " <<*ptr;
cout << "\n";
}
int main()
{
shared x;
x.set(1); // set a to 1
x.show();
return 0;
}
when i compile the piece of code i get following error
g++ static.cc
/tmp/cc7dngkw.o: In function `shared::show()':
static.cc:(.text+0x1a): undefined reference to `shared::ptr'
static.cc:(.text+0x4a): undefined reference to `shared::ptr'
collect2: ld returned 1 exit status
basically a class has three ways of storing methods and variables.
private:
public:
protected:
Nothing can access anything that is private, except other members of the class (in either public, protected, or private)
and derived classes cannot directly mess with them.
protected is exactly the same as private. Except derived classes can mess with stuff.
public, anyone can access, use, and change. This is where you put methods(functions) for getting and setting your private and protected members.
So if I had a variable that I didn't want any other part of my code to access without asking me, say an int that tells me an object's x position, I would do something like this:
1 2 3 4 5 6 7 8 9 10 11
///
///CLASS HEADER FILE
///
class object{
protected:
int xAxisPosition;
public:
void set_xAxisPosition(int toChangeXPositionTo);
int get_xAxisPosition();
};