Accessing private members

I have class
1
2
3
4
5
6
class Text{
	private:
		char* text;
	public:
                 void set(const Text &t);
};

When I define this function,
1
2
3
4
5
void Text::set(const Text &t){
	delete[] this->text;								
	this->text = new char[strlen(t.text) + 1];
	strcpy(this->text,t.text);
}

I can access the private member with t. i.e t.text is valid.
Now I have class
1
2
3
4
5
6
class Menu{
	private:
                //some code
	public:
                void push_back(const Text &option); 
}

When I define
1
2
3
void Menu::push_back(const Text &option){
           //I cant access option.text but can access every public members
}


I don't understand why.
That's how private members work. They can only be accessed by member functions of the class itself. In your case, Text::set() is a member function of class Text, so it can access the private member text. On the other hand, Menu::push_back is a member of class Menu, so it has no access to the private members of Text.

Menu::push_back(const Text&) probably should not have access to the private members of class Text. It suspect that it should copy the Text object into a collection of menu items.
I have a private *Text [] in Menu
Topic archived. No new replies allowed.