Prompt
Answer
Problem Overview
The task is to manipulate the SecretClass
in a way that the GetToken()
method returns "CODE" after running the externalFunction
. We will utilize inheritance to access the protected method SetTokenTo
.
Implementation Plan
Create a Derived Class:
- Inherit from
SecretClass
to use the protected methodSetTokenTo
.
- Inherit from
Implement
externalFunction
:- Use the derived class to change the token of the original
SecretClass
instance.
- Use the derived class to change the token of the original
Code Implementation
#include
// Assume SecretClass is defined as follows:
class SecretClass {
private:
std::string token;
protected:
void SetTokenTo(SecretClass& another) {
another.token = token;
}
public:
SecretClass(const std::string& token) : token(token) {};
std::string GetToken() const {
return token;
}
};
// Derived class to utilize protected method
class SecretManipulator : public SecretClass {
public:
SecretManipulator(const std::string& token) : SecretClass(token) {}
void ChangeToken(SecretClass& secret) {
// Set the token of the passed secret instance to the current token
SetTokenTo(secret);
}
};
// External function implementation
void externalFunction(SecretClass& secret) {
SecretManipulator manipulator("CODE"); // Create an instance with the desired token
manipulator.ChangeToken(secret); // Change the secret's token
}
Explanation of the Code
- Imports: We include the header
<string>
to usestd::string
. - Class Definitions:
SecretClass
: This class holds a token and provides public access to it.SecretManipulator
: A derived class that can invoke theSetTokenTo
method.
- Function
externalFunction
:- An instance of
SecretManipulator
is created with the token "CODE". - It then changes the token of the
SecretClass
instance passed to it by callingChangeToken
.
- An instance of
Usage Example
Here is how the entire implementation would work in a program:
#include
#include
// Assume the above code is inserted here
int main() {
SecretClass secret("FUTURE");
externalFunction(secret);
assert(secret.GetToken() == "CODE"); // This will pass if our function is correct
}
Conclusion
By utilizing inheritance and protected methods effectively, we achieved the goal of modifying the token
in SecretClass
without altering its encapsulation. This solution maintains clean object-oriented principles while meeting the problem requirements.
Description
This solution demonstrates how to change a private member variable in a class using inheritance and protected methods to access and set a token in the SecretClass
via an external function.