Accessing Private Members of the Base Class

Nov 3, 2008 at 2:55am
Its apart of the project assignment that they are defined as private not protected. I need to use this data in functions of my inherited class, manipulate the data and then send the new data back to the base class. Is this possible?
Nov 3, 2008 at 4:20am
yes, just use member functions of each class to retrieve and set the data from their respective classes.
Nov 4, 2008 at 1:27am
As noted above, yes, you would have to write a setter and getter for each of those private data of base class.

As you said, the data is private, hence it all meant is PRIVATE part of the base class so even the derived classes of the base class can not access them. Only way would be either a by a getter and setter, or a declaring them "protected".
in the base class.

To be clearer, the private data of an object/class are accessed only in the defining class (base) while others by their setter or getter methods, hence you would have to write a setter and getter for each method of those private members in the base class giving a scope of access to outer space.

The code would look like:

class base
{
private:
int p_data; // can be accessed within the base class only
public:
void set(int data) { p_data = data; } // change the private data
int get() { return p_data; } // get/retrieve the private data
};

class derived : public base
{
public:
// other stuff

void modify() {
int data = base::get(); // get the private data of base
data += 123; // do something to change
set(data); // set the changed into base
}
};

That is it. The modify() would do the job all you want to modify the private data of its parent object. (As you may have already knew, the derived object is a composition of its parent and its own)

Hope it is clearer now.

Good luck :)
Topic archived. No new replies allowed.