Accessing class member variables from Main?

Hello everyone,

Assuming i have a class Student that have the following member variables:

1
2
private:
vector<Objects> My_Object;


an Object can be a pen, a pencil or a block notes and so on...

now i push several object into the Student Objects vector...

How can i access the object from whitin the main?

If i try in a loop to cycle through all the Student Objects i get this error:

 
error: 'std::vector<CObject> Student::My_Objects' is private|


that sounds correct, cause, as the error say, std::vector<CObject> Student::My_Objects' is private.

What should i do to access this member variable correctly?

Make it public, or should i create a public function that returns the vector?

What is the best practice for this?

Thank you in advance.
Last edited on
What should i do to access this member variable correctly?
Make it public, or should i create a public function that returns the vector?

That really depends on what you're trying to do.

1) Making it public is probably the easiest, but generally a poor choice as it breaks encapsulation.

2) You could provide a getter that returns a copy of the vector. The downside of that is that any changes you make to the copy won't be reflected in the original vector. An okay choice if you don't need to change the original vector. Down side is the overhead of copying the vector.

3) You could provide a getter that returns a reference to the vector. Avoids the overhead of copying the vector and any changes will be reflected in the original vector. The downside is that you're exposing the implementation of My_Object.

4) My choice would be to provide a getter that returns a specific object from the vector. Either return the n'th object, or search the vector and return an object by type. This assumes you want to access a specific object rather than the entire collection. If you're going to search the vector for a specific object by type, a std::map might be a better choice.


Thank you for the reply.

The option 2 seems to fit my need, cause i'm just querying a number of student to know who have the pencil.

But what there should the need to swap the pencil beetween two students?

Getter and setter still the best choice?

Last edited on
whatever you're trying to do in main() with each element of that private vector, try to move that for-loop into a new member function of the class
Topic archived. No new replies allowed.