copy constructor

I have a class:
1
2
3
4
5
6
7
8
9
class myclass
{
    int *p;
    public:
        myclass(int i){ p=new int; *p=i; }
        myclass(const myclass &obj) { p=new int; *p=*obj.p; }
        int get_value(){ return *p; }
        ~myclass(){ delete p; }
};


obj.p is a private member.
but have no error. Why is that?
thanks
Why should you have an error? Because p is a private member, it can be accesed only from within the object (by the memberfunctions of that same object). And that is exactly what you're doing here.
I think myclass(const myclass & obj) {p=new int; *p=*obj.p; } is not the memberfunction of obj.
Sorry, I misunderstood your question and tought it was some private member of myclass.

*obj.p isn't the right syntax to acces a member, it should be either (*obj).p or (most commen used) obj->p. My compiler also gives an error when using your syntax ('p' is not a type), but maybe that's compiler-depended.
*obj.p is the right syntax. He's dereferencing 'p', not 'obj'. IE: *(obj.p)

Anyway...

I think myclass(const myclass & obj) {p=new int; *p=*obj.p; } is not the memberfunction of obj.


You're thinking about it the wrong way. Each invidual instance (object) of the class does not have its own member functions -- the class itself is what has the member functions. Therefore private members of any 'myclass' object can be access by any other 'myclass' object... but not by any other kind of object.
Topic archived. No new replies allowed.