101k views
1 vote
C++ BreakTheCode

In this task, you have to break the encapsulation.

Namely, the following code is loaded into the system:

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;

}

};

void externalFunction(SecretClass& secret);

int main() {

SecretClass secret("FUTURE");
externalFunction(secret);
assert(secret.GetToken() == "CODE");

}

assert works like this. If the parenthesized expression is true, then nothing happens. If the parenthesized expression is false, your solution fails with an RE error.

Your task is to implement the function

void externalFunction(SecretClass& secret);

so that the expression secret.GetToken() == "CODE" at the end of main in the assert brackets is true.

In addition to this function, you can implement other auxiliary functions / classes if they help you solve the problem. All your code will be inserted into the system between the SecretClass class and the main function.

Send only the function code, necessary libraries and auxiliary functions to the system /
classes. Everything else will be connected automatically.

User Kwhitejr
by
8.3k points

1 Answer

0 votes

Step-by-step explanation:

In order to break the encapsulation and modify the token value of the SecretClass instance, you can define a friend function within the SecretClass scope. This friend function will have direct access to the private and protected members of the class. Here's an example of how you can implement the externalFunction to modify the token value: #include <cassert>

#include <string>

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;

}

friend void externalFunction(SecretClass& secret); // Declare externalFunction as a friend

};

void externalFunction(SecretClass& secret) {

secret.SetTokenTo(secret); // Modify the token value using SetTokenTo function

}

int main() {

SecretClass secret("FUTURE");

externalFunction(secret);

assert(secret.GetToken() == "CODE");

return 0;

}

By declaring externalFunction as a friend of SecretClass, we can directly call the SetTokenTo function inside externalFunction to modify the token value of the SecretClass instance.

When you run the code, it will break the encapsulation and modify the token value from "FUTURE" to "CODE", making the assertion secret.GetToken() == "CODE" true.

User Karthik Bose
by
7.9k points