Matthew Miceli
Matthew Miceli

Reputation: 9

How to set two separate instances of a class equal to each other c++

I understand that, for classes, private members can only be accessed by public members. But does that apply for each discrete instance of a class or can the public member of one instance directly access the private member of another instance.

For example, say there are two instances of class: instance1 and instance2. And say that the class has a private member x and public members getX() and setX(). If I want to set instance1.x equal to instance2.x which if the following would be correct:

instance1.setX(instance2.x)

Or

instance1.setX(instance2.getX())

Upvotes: 0

Views: 1361

Answers (3)

Christopher Pisz
Christopher Pisz

Reputation: 4000

An instance of a class can see the private members of another instance of the same class.

An instance of a class cannot see the private members of another instance of a different class.

An instance of a class can see the public members of another instance of a different class.

When we say "can see", we mean that the members are in scope for the implementation of the class method.

class A
{
public:
    Foo() { x = 10; }                  // is legal
    Bar(A & another) {another.x = 12;} // is legal
private:
    int x;
};

int main()
{
    A a;
    A b;

    a.Bar(b);  // Is legal

    return 0;
}

Upvotes: 4

Daniel Langr
Daniel Langr

Reputation: 23497

Inside code of that class member functions or its friends you can use

instance1.setX(instance2.x);
instance1.x = instance2.x;
this->x = instance2.x;
x = instance2.x;

Otherwise, you need to write

instance1.setX(instance2.getX());

Upvotes: 1

frslm
frslm

Reputation: 2978

Well, think about where you call instance1.setX(). Let's say you call it in some function foo():

void foo() {
    ...

    instance1.setX(instance2.x);

    ...
}

If foo() is not a member nor friend of your Instance class, then it can't access instance2.x; you'd have to use a getter here: instance2.getX().

Otherwise, you can use either method: instance2.x or instance2.getX().

Upvotes: 0

Related Questions