Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class with static pointer

I don't understand pointers and references very well yet, but I have a class with static methods and variables that will be referenced from main and other classes. I have a variable defined in main() that I want to pass to a variable in this class with static functions. I want those functions to change the value of the variable that is seen in the main() scope.

This is an example of what I am trying to do, but I get compiler errors...

class foo
{
    public:

    static int *myPtr;

    bool somfunction() {
        *myPtr = 1;
        return true;
    }
};

int main()
{
    int flag = 0;
    foo::myPtr = &flag;

    return 0;
}
like image 594
Brian Avatar asked Aug 11 '11 22:08

Brian


People also ask

Can a pointer be static in C?

Static pointers in C/ C++ These variables holds their value even after they are out of their scope. Once declared and initialized they are not re-declared i.e., once the memory is allocated, then they exist till the termination of that program. A static pointer declaration as shown below.

Can we have a static pointer in C++?

You cannot use a pointer to member to point to a static class member because the address of a static member is not associated with any particular object. To point to a static class member, you must use a normal pointer. You can use pointers to member functions in the same manner as pointers to functions.

Can we assign pointer to a static variable?

Sure. It can assign a pointer to the address of a locally declared variable and then return it as the function result.

Is static pointer initialized to null?

Without an initializer, the values of static and extern pointers are automatically initialized to null pointers (pointers to memory location 0).


2 Answers

Provide the definition of the static variable outside the class as:

//foo.h
class foo
{
    public:

    static int *myPtr; //its just a declaration, not a definition!

    bool somfunction() {
        *myPtr = 1;
        //where is return statement?
    }
};  //<------------- you also forgot the semicolon


/////////////////////////////////////////////////////////////////
//foo.cpp
#include "foo.h"  //must include this!

int *foo::myPtr; //its a definition

Beside that, you also forgot the semicolon as indicated in the comment above, and somefunction needs to return a bool value.

like image 149
Nawaz Avatar answered Sep 20 '22 05:09

Nawaz


#include <iostream>
using namespace std;

class foo
{
public:

static int *myPtr;

bool somfunction() {
    *myPtr = 1;
    return true;
}
};
//////////////////////////////////////////////////
int* foo::myPtr=new int(5);     //You forgot to initialize a static data member  
//////////////////////////////////////////////////
int main()
{
int flag = 0;
foo::myPtr = &flag;
return 0;
}
like image 36
Shashank Singh Avatar answered Sep 21 '22 05:09

Shashank Singh