This is pretty basic, but I wanted to find out all the available options on how to do this.
I have a class with a variety of variables that are private, if I have another class which I want to be able to have access to some of the variables - what's the best option.
As far as I understand I could make it a friend of the class, or use inheritance. But this would give it access to many more variables than I would like, I'm guessing there's a better method.
For ease of understanding here's a simplified example:
class House
{
private:
int iRooms;
string sStreet;
float fHeight;
public:
House (int, string, float); //constructor
~House (); //destructor
};
class Appartment
{
// to have access to iRooms and sStreet only.
}
int main(){
House myHome(5,London,5.2);
Appartment myAppart;
return 0;
}
When you say "have access", do you mean you're going to pass an object to a method of the class and the method needs to access the members of the object, or that the class simply needs members of the same name?
Sorry maybe I'm being really stupid, or just not explaining myself properly. I'm new to C++ so bare with me if I make a mistake.
As in the example above, the class House has a member called iRooms. If in the class Appartment I want to have a member called say 'iAppart_Rooms' and this to be set equal to 2 * iRooms.
Im guessing I need a method within the Appartment class which sets
iAppart_Rooms = iRooms*2;
But as far as I understand iRooms is private, so I was wondering how to go about doing the above.
I know this must be really basic, but thanks to anyone who can help. Also a little bit of code will help me, seeing as saying 'get/set methods' doesn't really explain enough to a newbie.
The way your trying to implement your design is incorrect. There is no real defined relationship between House and Apartment that would cause you to consider friendship or inheritance.
Your trying to minimize code in some fancy way, and yes you can do this but it requires a bit more design. For an easy solution just add the variables you need to apartment also.
e.g
1 2 3 4
class Apartment {
int iRooms;
string sStreet;
};
Apartment doesn't need to access the variables of house because they are not related. Unless your terminology is different? An apartment is 1 unit within a building. A house is a stand-alone abode that has no relationship to an apartment.