static pointer data member

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

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include<string.h>
using namespace std;
class shared {
        public:
	static int *ptr;
	static int a;
	int b;
	void set(int i) {a=i;}
	void show();
} ;


file2 static.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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

Any help would be appreciated. thanks in advance.
Last edited on
You shouldn't try to access *ptr at all from outside of the class. It's private (thereby only methods of the class can access it)

Look into getters and setters. Also, I would recommend changing to protected, to further any classes you may want to derive from this class.

(edit) if you need more info, just ask, and I'll be glad to expound
Last edited on
can you please explain in brief. I have to compulsorily access that pointer in my code (as i am copying 30 bytes of data)
Alright, no problem.

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


1
2
3
4
5
6
7
8
9
10
11
///
///CLASS CPP FILE
///

void object::set_xAxisPosition(int toChangeXPositionTo){
xAxisPosition = toChangeXPositionTo;
}

int object::get_xAxisPosition(){
return xAxisPosition;
}



Last edited on
Topic archived. No new replies allowed.