shengy
shengy

Reputation: 9749

whats the difference in define an object's member a value, a pointer or a reference

I'm new to C++, and are confused about sth

I'm going to define a class, and when should I define a member a pointer? or when should I define a member a value? or when should I just define it as a reference?

what confused me is when I read the book TCPL 24.3.3 It said that "The pointer solution should be used when there is a need to change the pointer to the ‘‘contained’’ object during the life of the ‘‘containing’’ object. For example:

class C
{
    int a;
public:
    C(int i):a(i){};
};

class C2
{
    C a;
    C *p;
public:
    C2(int i):a(i), p(new C(i)){};
    ~C2(){delete p;}

    C ChangeValue(C c)
    {
        C temp = a;
        a = c;
        return temp;
    }

    C* ChangePointer(C *c)
    {
        C* temp = p;
        p = c;
        return temp;
    }
};

I think there is no difference using a valus as a class member....

please help me through this:)

Upvotes: 0

Views: 132

Answers (2)

Alok Save
Alok Save

Reputation: 206528

"The pointer solution should be used when there is a need to change the pointer to the ‘‘contained’’ object during the life of the ‘‘containing’’ object"

Pointers can be pointed to different object types.
References are just alias of types and cannot be bound to other types. They remain alias to the object to which they were bound at time of declaration.

For Example:

int i,j,k;
i = 10;
j=20;
k=30;
int *ptr;
ptr = &i;       //ptr now points to i
ptr = &j;       //ptr now points to j, Allowed!
int &ref = i;   //ref is alias of i
ref = j;        //Allowed BUT It assigns value of j to i and doesnt point ref to j

The statement means if you want your member variable to be pointing to different objects then it should be pointer then it should be reference.

Note: You can acheive same behavior for pointers as references by using const pointers.

Upvotes: 1

feathj
feathj

Reputation: 3069

The best way to think about pointers is "shallow copy" vs "deep copy". When I work with a particular object, is it ok that it will be duplicated when I pass it to a different scope (a different function or class)? If I don't want it to be copied, I should use a pointer, otherwise I can just declare it as a value (I should note that passing by reference is a way around this general rule).

Really it depends on your application. Sometimes I will design a particular class with pointers as members and then find out that it makes more sense to switch and vice-versa.

Upvotes: 2

Related Questions