Hi,
I am new to c++, facing difficulty in compiling the following code

#include <iostream>
#include<string.h>
using namespace std;

class myclass {
	public:
	int i, j, k, *l; // accessible to entire program
	static int *m;
};

int myclass::*m = NULL;
int main()
{
	myclass a, b, *p;
	a.i = 100; // access to i, j, and k is OK
	a.j = 4;
	a.k = a.i * a.j;
	b.k = 12; // remember, a.k and b.k are different
	p = &b;
	*b.l = 23;
	*b.m = 23;
	//memcpy(&b.m, &b.l, sizeof(int));
	cout << "with ptr = " << *b.l << *(p->l) <<endl;
	cout << a.k << " " << b.k << endl;
	return 0;
}

in the above code i can access value of l very easily, for testing purpose i declared m as static, as static variable have to be defined outside the class i am doing it like "int myclass::*m = NULL;", but when i try to access the value of m (*b.m = 23;) I get error following error in the compilation.

g++ ptr1.cc
/tmp/cc1L6oUM.o: In function `main':
ptr1.cc:(.text+0x45): undefined reference to `myclass::m'
collect2: ld returned 1 exit status

can anyone tell me where I am wrong?
Is there any thing wrong in defining static variable? or is there anything wrong in accessing the value?
Your help would be appreciable. Thanks in advance.

The * (star) that designates a pointer is linked to the type, not the variable name. That's why I prefer the convention int* ptr; instead of int *ptr; , just because it makes it more obvious that it is a variable of name "ptr" which is a pointer to an integer. In other words, the star qualifies the type, not the variable.

With this in mind, what is wrong with your implementation is that when you set the initial value of your static data member "m", you are putting the star in the wrong location (next to the name, not to the type). So here is the solution:

int* myclass::m = NULL;

That will make it compile, but there are definitely things that are wrong with your implementation, namely, you are dereferencing pointers that were never initialized to point anywhere (i.e. l and m).

What mike_2000_17 said, plus this:

// Your code ---->
	p = &b;    // Ok
	*b.l = 23; // Bad: member 'l' has not been initialized with a valid pointer
	*b.m = 23; // Bad: static member 'm' has not been initialized with valid pointer

	cout << "with ptr = " << *b.l << *(p->l) <<endl; // Bad - see above.

// Better code ---->
        static int ll = 23;
	p = &b;
	b.l = &ll;
	b.m = &ll;

	cout << "with ptr = " << *(b.l) << *(p->l) <<endl;

Edited 5 Years Ago by rubberman: n/a

This article has been dead for over six months. Start a new discussion instead.