Secure Access in C ++

In any case, I can access the protected variable in the class without inheritance.

class ClassA{
  protected:
    int varA; 
};

class ClassB{
  protected:
    ClassA objectA;

};


ClassB theMainObject;

I would like to access varA through a MainObject.

+3
source share
8 answers

I assume that modifying the ClassA definition is not allowed.

Here's a tricky way for you, but I do not recommend you use it :)

class ClassA
{
protected:
   int varA; 
};

class ProtectedRemover // magic thing
{
public: // <- Note this! :)
   int varA;
};

class ClassB
{
protected:
   ClassA objectA;

public: // Just add two methods below

   int getProtectedVarA()
   {
      return reinterpret_cast<ProtectedRemover*>(&objectA)->varA;
   }

   void setProtectedVarA(int i)
   {
      reinterpret_cast<ProtectedRemover*>(&objectA)->varA = i;
   }
};

int main()
{
   ClassB theMainObject;

   // Set protected thing.
   theMainObject.setProtectedVarA(3); 

   // Get protected thing.
   std::cout << theMainObject.getProtectedVarA() << std::endl;
}

Thus, there is a way to access and modify secure / private data.
Who thought this was impossible, vote;)

0
source

You can make a classBfriendclassA

class ClassA{
  protected:
    int varA; 

  friend ClassB;
}

but using accessories is likely to be better since you don't bind classes together.

class ClassA{
  int getA() { return varA;}
  void setA(int a) { varA = a; }
  protected:
    int varA; 
}
+5
source

:

public:
   int getVarA(){return varA;}
+3

getter/setter:

int ClassA::GetVarA()  
{  
    return varA;
}  
BOOL ClassA::SetVarA(int nNewVar)  
{  
    // Perform verifications on nNewVar... Return FALSE if didn't go well.  

    // We're satisfied. Set varA to the new value.  
    varA = nNewVar;  

    return TRUE;
}
+2

friend . , , , , !

+1

, , varA theMainObject. protected - , private (, ), varA . API ClassA .

varA ClassA, , :

public:
   int getVarA() const
   {
       return varA;
   }
+1

, ClassB ClassA, , ClassA. Herb Sutter .

+1

Mark B, , , , ProtectedRemover classA ....

, , :

class ClassA
{
protected:
   int varA; 
};

class ProtectedRemover : public ClassA // now, they are related!
{
public: // <- Note this! :)
   int getA() { return varA; }
   void setA( int a ) { varA = a; }
};

class ClassB
{
protected:
   ClassA objectA;

public: // Just add two methods below

   int getProtectedVarA()
   {
      return ((ProtectedRemover)*(&objectA))->getA();
   }

   void setProtectedVarA(int i)
   {
      ((ProtectedRemover)*(&objectA))->setA(i);
   }
};

, .... , , ProtectedRemover classA ... , ClassA !

Still not recommended if you really have no other choice (I can’t change classA by creating my class friend or adding settre / getter)!

Nothing is really possible ....

0
source

All Articles