What should you do gain access to Private Base Class Data

Questions by prettyfox

Showing Answers 1 - 4 of 4 Answers

j_l_larson

  • Oct 18th, 2009
 

F. None of the above are entirely the right answer

You can provide a method in the base class to allow the private data to be read or written and then provide an access specifier in the derived class which allows the methods to be called.  For example:

class Base {
public:
  Base() : m_nDerivable(1), m_nSecret(0) {}
  ~Base() {}
  int ReadBasePrivateData() { return m_nSecret; }
  void ModifyBasePrivateData( int n ) { m_nSecret = n; }
  int foo() { return m_nSecret + m_nDerivable; }
protected:
  int bar() { return m_nSecret + m_nDerivable; }
  int m_nDerivable;
private:
  int woozle() { return m_nSecret + m_nDerivable; } // can never be called, even with access specifiers
  int m_nSecret;
};

class PrivDeriv : private Base {
public:
  PrivDeriv() {}
  ~PrivDeriv() {}
  Base::ReadBasePrivateData; // access specifier, we are allowed to read base's private things 
  Base::ModifyBasePrivateData; // access specifier, we are allowed to write over base's private things
  Base::foo; //public member allowed
  //Base::bar; //protected member can be allowed, but we selectively block it here
  //Base::woozle; //private can not be allowed - compiler error
  //int GetBasePrivateInt() { std::cout << "private derived get base private membern"; return Base::m_nSecret; } // compiler error 
  int GetBaseProtectedInt() { std::cout << "private derived get base protected membern"; return Base::m_nDerivable; }
private:
};

int main( int argc, char** argv ) {
  PrivDeriv a;
  a.foo(); // allowed
  //a.bar(); // compiler error
  //a.woozle(); // compile error
  int nPrivateInt = a.ReadBasePrivateData();
  std::cout << "private int is allowed through public read method: " << nPrivateInt << "n";
  a.ModifyBasePrivateData( 10 ); // inaccessible, compiler error
  nPrivateInt = a.ReadBasePrivateData();
  std::cout << "private int has been changed through public write method: " << nPrivateInt << "n";
  return 0;
}

  Was this answer useful?  Yes

B. You should use a public or protected base class function.

Example:

class Base
{
private:
    int a;
public:
    Base() {a = 5;}                         //Initialize variable a;
    int AccessPrivate() {return a;} //access private member using public function
};

class Derived: public Base
{
public:
    int getData() {return AccessPrivate();}  //derived class returns private data of base
};

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions