I am working on C++ application in which I focus on changing the implementation of my code to make it more secure, but I do have a couple of questions. How can a variable with the same name be used and not conflict with each other in c++ code? How can a parameter be named the same as a variable in the same class? What is 'this->name'? Why should never have direct access to an objects' attributes (variables)?
The first of two things I would like to change would be the following: change the access designation in the classes to prohibit the line that has the fido.name and how can I add content to the classes (both Dog and Cat) to permit access to the variables so that I can access the name attribute? Here is my source code and picture of a command prompt of what it looks like before the implementation. I know that it is going to output the command prompt I have attached below, but what steps do I need to do to implement the changes I would like to see above?
The first of two things I would like to change would be the following: change the access designation in the classes to prohibit the line that has the fido.name and how can I add content to the classes (both Dog and Cat) to permit access to the variables so that I can access the name attribute? Here is my source code and picture of a command prompt of what it looks like before the implementation. I know that it is going to output the command prompt I have attached below, but what steps do I need to do to implement the changes I would like to see above?
Code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Dog {
public:
string name;
public:
// constructor
Dog (string name) {
this->name = name;
cout << "Dog's name is " << name << endl;
}
};
class Cat {
public:
string name;
public:
// constructor
Cat (string name) {
this->name = name;
cout << "Cat's name is " << name << endl;
}
};
int main () {
Dog fido ("Fido");
Cat spot ("Spot");
// These 2 lines of code break the object-oriented paradigm in a major way
cout << "From main, the Dog's name is " << fido.name << endl;
cout << "From main, the Cat's name is " << spot.name << endl;
cout << "Hit any key to continue" << endl;
system ("pause");
return 0;
}
Comment