Basically I have this class that has a member function that builds a vector of a certain struct.
Example:
struct Something
{
string something1;
int something2;
};
class classThing
{
public:
void buildsomething(){...};
private:
vector<Something> something;
};
Basically, since something is private to classThing, other classes would not be able to access it. What can I do in order to make it available to other classes or even functions aside from making it public?
Derive the other classes from classThing, if there is some relation to them.
Pass objects of otherClass to a member of classThing. Then you can iterate through the vector, passing each Something to a member of otherClass.
My advice: you need to rethink what should hold the vector of Something and if the members of otherClass really should or should not be members of classThing.
I've wrestled with the problem a lot learning C++. My spanner util has undergone major rewrites as a result.
Basically I think deriving the other classes will not be the proper thing to do since the two classes are somehow unrelated. And making the other class friend results in this error:
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\fstream(890): error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\ios(176) : see declaration of 'std::basic_ios<_Elem,_Traits>::basic_ios'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> This diagnostic occurred in the compiler generated function 'std::basic_ifstream<_Elem,_Traits>::basic_ifstream(const std::basic_ifstream<_Elem,_Traits> &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.56
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
i think it has something to do with the ifstream type that is inside the class that I want something from.
This is not a particularly good idea; it makes the code hard to read and maintain; and it is prone to all kinds of programming errors (for instance a simple typo with the case of the first letter)
Prefer not using identifiers which differ only in the case of letters, instead consider something like: vector<Something> many_things ;
> Basically, since something is private to classThing, other classes would not be able to access it.
> What can I do in order to make it available to other classes or even functions
> aside from making it public?
Provide a public accessor function, perhaps? These are some of the ways it could be done: