Jump to content

Accessing private data member

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
6 replies to this topic

#1
boredaxel

boredaxel

    Newbie

  • Members
  • PipPip
  • 10 posts
Is it possible for an instance of a class to access the private data member of another instance of the same class?

#2
solartic

solartic

    Learning Programmer

  • Members
  • PipPipPip
  • 95 posts
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
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
If you declare one class to be a friend of the other class, yes.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#4
boredaxel

boredaxel

    Newbie

  • Members
  • PipPip
  • 10 posts
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

#5
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Currently, your code snippet does nothing... I'm not clear on what you think is happening.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#6
boredaxel

boredaxel

    Newbie

  • Members
  • PipPip
  • 10 posts
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?

#7
julmuri

julmuri

    Programmer

  • Members
  • PipPipPipPip
  • 139 posts

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 ).