Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a private nested class in C++?

I found a question in CPP quiz. The question is

class secret
{
    class hidden{};
public:
    template <class K>
    string accept(K k) {return (k(*this, hidden()));}
    string keyToNextLvl (hidden )const {return ("success!");    }
};

struct SampleSoln
{
    template <class pwd>
    string operator()(const secret &sc, pwd opwd) const
    { return   (sc.keyToNextLvl(opwd)); }
};
int main() 
{
    secret sc;
    cout <<sc.accept(SampleSoln()) << endl; //Prints success
    cout <<sc.keyToNextLvl (AnswerKey()) << endl; //Need to provide the implementation of AnswerKey
}

Now I have to access it using a the method "keyToNextLvl" directly. (I am not allowed to access the accept method -sample solution is provided in the ques itself for accessing keyToNextLvl using accept method. So I need to provide the implementation of AnswerKey)

I did a some search and got some ways to access a private members/methods without using friend http://bloglitb.blogspot.in/2010/07/access-to-private-members-thats-easy.html

But I didn’t get any idea for the solution of above ques.

like image 641
SathishSrinis Avatar asked Jan 01 '26 18:01

SathishSrinis


1 Answers

Got it!

struct AnswerKey
{
  template <class T>
  operator T ()
  {
    return T();
  }
};

uses a templated conversion operator to construct a secret::hidden object

like image 71
kmdreko Avatar answered Jan 03 '26 07:01

kmdreko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!