Sunday, 15 March 2015

c++ - (Copy Constructor) How does the object passed as parameter to initialize another object have access to the private members? -



c++ - (Copy Constructor) How does the object passed as parameter to initialize another object have access to the private members? -

example code:

class { int x; public: my(int a) { x = a; } my(my &obj) { x = obj.x; } . . } int main(void) { object1(5); object2(object1); homecoming 0; }

how object2 initialized passing object1? far can see object1 can't access fellow member x directly, how help in initializing object2?

access command (public/private/protected) controls whether piece of code can legally refer a name of class's member. individual objects don't play role here; whole problem code , names.

let's compare constructor question, friend function , free function:

class { int x; friend void fr(my&); public: my(my &obj) { x = obj.x; } }; void fr(my &obj) { obj.x += 1; } void nonfr(my &obj) { obj.x += 2; }

take statement x = obj.x;. statement piece of code. piece of code? within constructor of class my. it's part of class , can access name obj.x.

next, statement obj.x += 1;. piece of code? within function fr, friend of class my. it's friend, can access name obj.x.

finally, statement obj.x += 2;. piece of code? within function nonfr. nonfr ordinary function unrelated class my, has no right access names of private (or protected) members of class my, fail compile.

side notes:

normally, re-create constructor should take parameter reference const, this:

my(const &obj)

copy constructors take non-const reference can modify source object, , viable utilize cases them extremely rare. not mention prevent copying temporaries, since can't bind non-const references.

also, it's preferable utilize mem-initialiser-lists instead of assignment within constructor, because latter first initialises fellow member , assings it. in total, constructor should this:

my(const &obj) : x(obj.x) {}

not mention fact unless need special handling in re-create constructor (which don't here), shouldn't declare @ , allow compiler generate you. see rule of 0 , rule of three more information.

c++ class object

No comments:

Post a Comment