Devesh Agrawal
Devesh Agrawal

Reputation: 9212

Why compilation error when accessing private members of the same class

Why this program giving compilation error:

proxy.cpp: In member function ‘void ProxyCar::MoveCar()’: proxy.cpp:59: error: ‘int Driver::age’ is private proxy.cpp:81: error: within this context

class Car
{
    public:
        void MoveCar()
        {
                cout << "Car has been driven";
        }
};

class Driver
{
    private:
         int age;

    public:

        int get() { return age; }
        void set(int value) { age = value; }
        Driver(int age):age(age){}
};

class ProxyCar
{
    private:
        Driver driver;
        Car *realCar;

    public:
    ProxyCar(Driver driver): driver(driver), realCar (new Car) {}

    void MoveCar()
    {
        if (driver.age <= 16)
          cout << "Sorry the driver is too young to drive";
        else
            realCar->MoveCar();
    }
};

int main()
{
        Driver d(16);
        ProxyCar p(d);
        p.MoveCar();
        return 0;
}

I am trying to access the Driver object inside ProxyCar. This line is causing the error. if (driver.age <= 16)

Upvotes: 0

Views: 1176

Answers (3)

HAL
HAL

Reputation: 3998

Driver::age is a private member of class Driver. Hence, it is only accessible to the members of class Driver

However, you may use accessor methods to let the outside world access the private members.

class Driver
{
    private:
        int age;

    public:
        int get_age() { return age; }
};

And use the accessor method to get the private members of the class.

if (driver.get_age() <= 16)
    cout << "Sorry the driver is too young to drive";
else
    realCar->MoveCar();

For more on access modifiers: http://en.wikipedia.org/wiki/Access_modifiers

Upvotes: 3

Hariprasad
Hariprasad

Reputation: 3640

Because age is a private member in the Driver class.

Do you intent to do this:

     if (driver.get()<= 16)
         cout << "Sorry the driver is too young to drive";
     else
         realCar->MoveCar();

Upvotes: 4

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71009

You are accessing a private member of Driver. This is a separate class and you have no visibility to its private members.

Upvotes: 0

Related Questions