mister
mister

Reputation: 3433

Store Non-Static Object in Class with Static Functions

i have two classes (non-static) A & (static) B. I am trying to store Object A into B so that i can use its functions in funcB(). However i do know that static classes cannot store non-static variables & functions. is there anyway to get pass this rather than converting Class A into a static class?

class A
{
   public:
          A();
          void funcA();
   private:
          int A;
};

class B
{
   public:
         B(A *objA);
         static void funcB();
   private:
         A *objA;
};

edit: I stated static class to make it easier to explain. i did not know the correct term. So the question is actually: How do i use a non-static member from a static function?

Upvotes: 0

Views: 770

Answers (2)

David D
David D

Reputation: 1591

You can not access anything that is specific to an instance of a class from a static function by itself. A static function has no "this" pointer (the compiler passes a pointer to the instance of the object calling the function for non-static functions). You can get around this by passing a pointer to the object you want to modify, but then why are you using a static function? My advice would be to avoid what it seems like you are trying to do, but I provided 2 ways to do it below (as a good learning example).

See below for an example of using

    #include <iostream>

using namespace std;

class A
{
   public:
    A(int value) : a(value){}
          void funcA();
   public:
          int a;
};

class B
{
   public:
         B()
         {
             objA = new A(12);
         }

         void funcB2()
         {
             B::funcB(*objA);
         }

         static void funcB(A const & value)
         {
            cout << "Hello World! " << value.a << endl;
         }

   private:
         A *objA;
};

int main()
{
    A a(10);
    B::funcB(a);

    B b;
    b.funcB2();
    return 0;
}

Upvotes: 1

lai
lai

Reputation: 112

I think you just should not make design like this. A static function is initialized when the non-static members are not ready. You said "the class A, links to many other classes and has stored many other information. Class B on the other hand, has to be static due to some windows API threading condition." . In this case, can you change your design and turn A into static class?

Upvotes: 0

Related Questions