Possible Duplicate:
With a private modifier, why can the member in other objects be accessed directly?
Private members of a C++ class are designed to be invisible to other class instances. I'm confused since private members can be accessed as shown below! Can anyone explain it to me?
Here's my code:
#include <iostream>
using namespace std;
class Person
{
private:
char* name;
int age;
public:
Person(char* nameTemp, int ageTemp)
{
name = new char[strlen(nameTemp) + 1];
strcpy(name, nameTemp);
age = ageTemp;
}
~Person()
{
if(name != NULL)
delete[] name;
name = NULL;
}
bool Compare(Person& p)
{
//p can access the private param: p
//this is where confused me
if(this->age < p.age) return false;
return true;
}
};
int main()
{
Person p("Hello, world!", 23);
return 0;
}
We cannot access a private variable of a class from an object, which is created outside the class, but it is possible to access when the same object is created inside the class, itself.
We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class.
In general, private variables are those variables that can be visible and accessible only within the class they belong to and not outside the class or any other class. These variables are used to access the values whenever the program runs that is used to keep the data hidden from other classes.
No, it is a syntax error, you can not use access modifiers within a method.
Methods of a class can access its private attributes throughout all class instances, at least in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With