Quote:
I want to be able to reach them through the derived class itself, not main().
Confusion probably arises here because the name, the value, and the visibility of a member variable within a class are not cleanly differenced. Basically, one must clearly differentiate between the name and the value of a variable. In each instance of a class, there are variables with the same name, but each variable has its own value.
Additionally, one can still specify the visibility of a member variable. This determines whether a caller of the class can see it at all. The usual way to set up controlled access to member variables was already mentioned by Rick York. A setter for the variables is in the program above the method assign() a suitable counterpart, e.g., readout() would make it possible to read the variables again.
One could add, still, that with the production of a derived class always also its own instance of the parent class is produced. A possible confusion here, or one could call it also problem in the program above, could be prevented, if one does not create an instance of the parent class, since this happens anyway automatically each time.
If one would like that in principle always in all derived classes the variables of the parent class also have the same value, still the keyword "static" could be a solution.
class derived_class :parent_class {
private:
int private3;
public:
void assign(int p1, int p2, int p3);
void readout(int &p1, int& p2, int& p3);
};
The call could then look like this:
derived_class derived1;
derived1.assign(20, 32, 45);
printf("\nDerived Class Variables:");
int p1, p2, p3;
derived1.readout(p1, p2, p3);
cout << "private1 = " << p1 << "private2 = " << p2 << "private3 = " << p3 << endl;
An alternative instead of reading out all variables at once with readout() would be to read them out individually, e.g. with int get_p1().
One more note about the code above : With C++, the output stream cout should be used instead of the C function printf() for good reasons.