Boolean
Boolean

Reputation: 17

How can i see the difference between address and value c++ class?

I have a problem in pointers and reference understanding. I have the following snippet:

class U
{
protected:
    int m;
public:
    U(int m = 0) : m(m) {}
    virtual void f() { cout << "U::f() @ m = " << m << endl; }
};

class V : public U
{
    int n;
public:
    V(int m, int n) : U(m), n(n) {}
    void f() { cout << "V::f() @ m = " << m << ", n = " << n << endl; }
};

int main() {
    V v1(1, 1), v2(2, 2);
    v1.f();
    v2.f();
    U* u = &v1;
    *u = v2;
    v1.f();
    v2.f();
}

I run this and the output is:

V::f() @ m = 1, n = 1
V::f() @ m = 2, n = 2
V::f() @ m = 2, n = 1
V::f() @ m = 2, n = 2

I don't understand the third line of output: V::f() @ m = 2, n = 1. Why m is changed to 2?

Upvotes: 0

Views: 111

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 5882

first of all *u = v2; doesn't make u point to v2 . first u is dereferenced and it is equivalent to (U)v1 = v2;

Since class U only contains U::int m so only m is modified using assignment operation.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227418

*u=v2;

This doesn't make u point to v2. It assigns v2 to the U sub-object of the object that u points to, i.e. to the U part of v1. This is because *u is a U object.

Upvotes: 3

Related Questions