In: Computer Science
Write C++ code that prompts the user for a username and password (strings), and it calls the login() function with the username and password as arguments. You may assume that username and password have been declared elsewhere. Use virtual functions, pure virtual functions, templates, and exceptions wherever possible. Please explain the code.
Your code should print error messages if login() generates an exception:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Base//base class declared which is storing the required password and username
{
string user = "ak2783934"; //user name saved here
string password = "password1"; //password saved here
public:
virtual void usernameRetrieve() = 0; //pure virtual function
virtual void passwordRetrieve() = 0; //pure virtual fucntion
string getUser() { return user; }
string getPass() { return password; }
};
class Derived : public Base//derived class declared for accessing the forbidden values of passwords and username
{
string username;
string password;
public:
string getUsername() { return username; }//member function for getting username from the base variable
string getPassword() { return password; }//member function for getting password from the base class
void usernameRetrieve() { username = getUser(); }
void passwordRetrieve() { password = getPass(); }
};
void login(string username, string password)
{
Derived loginDetails;
loginDetails.usernameRetrieve();//retrieving username
loginDetails.passwordRetrieve();//retrieving password
bool userMatched;
if (username == loginDetails.getUsername()) //if username matched then make usermatched = true
userMatched = true;
else
userMatched = false;
bool passMatched;
if (password == loginDetails.getPassword())//if password matched then make the passMatched = true
passMatched = true;
else
passMatched = false;
try //exception block
{
if (!userMatched or !passMatched)//if any of them is false then throw an exception
{
if (userMatched == false)
throw userMatched;
else
throw passMatched;
}
}
catch (bool userMatched) //check if exception is thrown with userMatched
{
cout << "User not found" << endl;
}
catch (bool passMatched) //check if the expcetion is thrown with passMatched
{
cout << "Password did not match" << endl;
}
if (userMatched and passMatched)//if both of them is matched then we print login succesful
{
cout << "Login successful" << endl;
}
}
int main()
{
cout << "Enter the username: ";//asksing for username
string username;
cin >> username;
cout << "Enter the password: ";//asking for password
string password;
cin >> password;
login(username, password);
}
I declared a base class which is used for storing the details of the user but as we are not using any kind of database so I have not thrown the other exceptions. As the question has asked to prompt the user to enter password and username I have done the same and also using private of the base class the username and password are not exposed to outer code.