How do I access a private variable in a base class from a derived class? (C++)?

I would like some help on how to do this, here is an example:

A Car class is a base class with a private variable called colour which is originally set to 0.

Then I create a derived class called Mini and want to set the colour to be 1 and output the colour. So the code for the function that I would type in the mini would be:

void Mini::ShowColour(void)

{

colour = 1;

cout << "The colour of the Mini is " << colour << endl;

}

But if I type this it says that I can't access private variables from the Car class. What do I do, can any one help me?

Comments

  • Hi,

    I wrote a similar program to yours just now. Check it out:

    Note that you cannot access a private member directly, instead do it through a public function.

    #include <iostream>

    using namespace std;

    class Car{

    int colour;

    public:

    void setValue(int x){

    colour = x;

    }

    int getValue(){

    return colour;

    }

    };

    class Mini : public Car{

    public:

    void changeValue(int x){

    Car::setValue(x);

    }

    };

    int main(){

    Car c;

    c.setValue(5);

    cout<<c.getValue()<<endl;

    Mini m;

    m.changeValue(465);

    cout<<m.getValue()<<endl;

    return 0;

    }

    The output is

    5

    465

    Amare

  • Ideally, all object state variables are private, and subclasses see the same interface to the base class object as every other class does. The protected attribute is a nod to practicality. The point of having a hidden implementation is so that you can upgrade them without rewriting the clients that use the code. If a class has protected data members, you can't change those without rewriting any subclasses that use them. Purists will likely say never use protected. I say "almost never". If you have a class that isn't widely-used, but has performance issues that can be improved by short-circuiting the object formality a bit, then protected members can be a winner. C# even defeats the laziness excuse for using protected fields. With properties, you can make getter/setter methods behave just like data.

  • Make the derived class "Mini" a protected class. That means it allows the derived class to access the private variables inherited from Car.

    However, if you were to use Java or possibly other programming languages for object oriented programming, you cannot directly access private variables. When this occurs, you have to create methods to alter those variables.

  • If your class' name is Mini then it should work. But if you have a class called CarClass and another class called Mini, then the only way you're going to access those private variables from CarClass is if you make Mini a derived child class from CarClass and set a pointer to the variable 'Colour'.

    Other then that it should work if it's all in the same class.

    - Hex

Sign In or Register to comment.