Is it possible for an instance of a class to access the private data member of another instance of the same class?
Accessing private data member
Started by boredaxel, Feb 22 2009 10:45 AM
6 replies to this topic
#1
Posted 22 February 2009 - 10:45 AM
|
|
|
#2
Posted 22 February 2009 - 11:05 AM
well if you have a accessor method to the private data member and that data member is also static, then yes. but otherwise i don't think u would be able to.
#3
Posted 22 February 2009 - 02:12 PM
If you declare one class to be a friend of the other class, yes.
#4
Posted 23 February 2009 - 04:59 AM
I mean something like this:
//This is a copy constructor that copies the
//private data member aList from aStack to
//Stack.
Stack::Stack(const Stack& aStack)
: aList(aStack.aList)
{}
I was wondering why a Stack constructor can access the private data of another instance. Isit because both are of Stack class? Is this allowed? Thanks
//This is a copy constructor that copies the
//private data member aList from aStack to
//Stack.
Stack::Stack(const Stack& aStack)
: aList(aStack.aList)
{}
I was wondering why a Stack constructor can access the private data of another instance. Isit because both are of Stack class? Is this allowed? Thanks
#5
Posted 23 February 2009 - 08:40 AM
Currently, your code snippet does nothing... I'm not clear on what you think is happening.
#6
Posted 23 February 2009 - 08:54 AM
class List {
private:
...........
public:
//This is a constructor that copys elements in alist to the new list
List(const List& alist)
{......}
};
class Stack
{
public:
Stack(const Stack& aStack) : aList(aStack.aList) {}
~Stack() {}
private:
List aList;
};
I hope this code is snippet is clearer. My question is why can the constructor in Stack class access the private data of the object aStack?
private:
...........
public:
//This is a constructor that copys elements in alist to the new list
List(const List& alist)
{......}
};
class Stack
{
public:
Stack(const Stack& aStack) : aList(aStack.aList) {}
~Stack() {}
private:
List aList;
};
I hope this code is snippet is clearer. My question is why can the constructor in Stack class access the private data of the object aStack?
#7
Posted 23 February 2009 - 10:46 AM
boredaxel said:
I hope this code is snippet is clearer. My question is why can the constructor in Stack class access the private data of the object aStack?
Just as you suspected, its because they are of the same class ( Stack ).


Sign In
Create Account


Back to top









