I am working on classes and am having an issue sending a request to the compiler to gain access to private designated variables but according to my guide it should be allowed in this instance. Both VS Express and Watcom compilers are denying access, is there something I can do to change this error situation besides simply making that data public?
// defines constructor, destructor, and range() function inline
#include <iostream>
usingnamespace std;
// declare the vehicle class
class Vehicle {
// These are now private
int passengers;
int fuelcap;
int mpg;
public:
// This is a constructor for Vehicle
Vehicle(int p, int f, int m) {
passengers = p;
fuelcap = f;
mpg = m;
}
// compute and return the range
int range() {return mpg*fuelcap;}
// Accesor functions
int get_passengers() {return passengers;}
int get_fuelcap() {return fuelcap;}
int get_mpg() {return mpg;}
};
int main() {
// Pass values to Vehicle constructor
Vehicle minivan(7,16,21);
Vehicle sportscar(2,14,12);
int range1, range2;
// Compute the ranges
range1 = minivan.range();
range2 = sportscar.range();
cout << "Minvan can carry " << minivan.passengers <<
" passengers with a range of " << range1 << " miles" << "\n";
cout << "Sportscar can carry " << sportscar.passengers <<
" passengers with a range of " << range2 << " miles" << "\n";
return 0;
}
Vehconst2.cpp (48) : error C2248: 'Vehicle::passengers' : cannot access private member declared in class 'Vehicle'
Vehconst2.cpp (11) : see declaration of 'Vehicle::passengers'
etc,,,,
Members are private if you don't want to give access to them outside the class.
If you want to access them or make them public or write a get/set function - you already have the getter function: get_passengers -
thanks bazzy, I didnt want to make the members public(I did briefly to test the program), and according to the guide I am learning from presently, I should have been able to access them in the above program(with a disclaimer that 'some' compilers would have a problem) however, I was surprised both compilers I used did not allow access .
you will NEVER get access of private members in non-friend functions
If a compilers allows that, it's non standard http://www.cplusplus.com/doc/tutorial/classes/
You need to call get_passengers if you want to get the values of passengers