Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A private variable can be accessed from another object of the same type? [duplicate]

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; 
}
like image 686
Triumphant Avatar asked Dec 23 '12 02:12

Triumphant


People also ask

Can a private variable be accessed from a object?

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.

Can a private variable be accessed from another class?

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.

What is a private variable?

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.

Can private variables be used in methods?

No, it is a syntax error, you can not use access modifiers within a method.


1 Answers

Methods of a class can access its private attributes throughout all class instances, at least in C++.

like image 139
Phil Rykoff Avatar answered Sep 23 '22 13:09

Phil Rykoff