NoOne NoOne - 20 days ago 5
C++ Question

C++ access to static class member variables, not friend

I'm sorry in advance if this is a stupid or nonsense question, but:

Can a non-constant static class variable for one class be used by another class without using friend or base/derived classes? The (abbreviated) situation is:

class Decl {
public:
static string searchVal;
... (other irrelevant stuff)
};

class Conj {
public:
static string searchVal;
... (other irrelevant stuff)
};

I don't want to repeat searchVal in both classes, and because of the rest of the program, I'm not keen on using friend (but I will if it's the only option).

Answer

Since your static members are public, if your class definitions are both visible, then their static members can be accessed using Decl::searchVal or Conj::searchVal respectively.

For example

class Decl 
{
     public: static string searchVal;
};

class Conj
{
    public:
        static string searchVal;
};

// within ANY function, including members of either class above
//    ... as long as both definitions above are visible to the compiler

 if (Conj::searchVal == Decl::searchVal)
 {
       // do something
 }  
Comments