static + pointer and reaching the private field of another class

M

mehmet canayaz

I have a class called foo and my class foo has a private field called
"name".
In my bar.cpp file i have #includes "foo.h" and in bar.cpp I also have
a STATIC function that duplicates an array of pointers to objects type
of foo by duplicating the objects themselves.

So, I had to call the constructor of foo class which must take in the
name to initialize the private name field. To get the name, I
implemented a function called get_name() that returns the name field of
the foo objects.
Everything was fine, get_name () was returning names each of the foo
objects the pointers in the array were pointing to, and I was putting
them in another array as I was taking copies of their values to new
objects.

But I saw an implementation of the same static function that was able
to see the private field "name" using pointers such as :

foo x = new foo ( my_array->name)

so as he incremented my_array he was creating new foo objects and
copying them in another array, and this was working..

I do not understand how this works because bar.cpp and foo.cpp has
nothing in common except bar.cpp includes foo.h . is this is enough for
bar to be able to see the private field of foo objects? -I dont think
so -
Does it have anything to do with static ? or pointers?

ps: when we changed the second implementation as
foo x = new foo (*my_ar.name )
it didn't work.


Thanks for reading and looking forward to hearing from you,
sincerely,
mehmet canayaz
 
V

Victor Bazarov

mehmet canayaz said:
I have a class called [...]

We much better understand C++ here. Why don't you simply post your
code instead of explainging what it is?
But I saw an implementation of the same static function that was able
to see the private field "name" using pointers such as :

foo x = new foo ( my_array->name)

so as he incremented my_array he was creating new foo objects and
copying them in another array, and this was working..

I do not understand how this works because bar.cpp and foo.cpp has
nothing in common except bar.cpp includes foo.h . is this is enough for
bar to be able to see the private field of foo objects? -I dont think
so -
Does it have anything to do with static ? or pointers?


Probably. I don't see any static or pointers in your post, though.
Try again, and this time post C++.
ps: when we changed the second implementation as
foo x = new foo (*my_ar.name )
it didn't work.


Probably because . has higher precedence than *. Try

foo x = new foo( (*my_ar).name );

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top