Cannot access protected member

I have a class I'm working on that deals with inheritance but I have a problem that is giving me a headache... I am trying to inherit members of the base class but no matter what I do the compiler tells me that "the member is inaccessible". Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class house{

protected:
	int coordinateX;
	int coordinateY;
	int coordinateZ;

public:
	void setCoordinates(int x, int y, int z){
		coordinateX = x;
		coordinateY = y;
		coordinateZ = z;
	}
};

class x3y2z1: public house{

};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include "House.h"
using namespace std;

int main(){

	x3y2z1 roomEntrance;

	roomEntrance.setCoordinates(3, 2, 1);

	cout<<roomEntrance.coordinateX;

	cin.ignore();
	cin.get();
	return 0;
}


On line 12 of the second block of code, I get an error saying that coordinateX is inaccessible. Can anybody tell me how to fix this? I've tried everything that I know and googled the problem.

Please help if you can.


EDIT:: Edited to fix a stupid mistake. The problem still applies.
Last edited on
"private" means that the data members are directly accessible only to the class in which they are declared (house). "protected" means that the data members are directly accessible to the class in which they are declared AND derived classes (x3y2z1). "public" means that the data members are directly accessible to the class in which they are declared, derived classes, AND all other code as well.
Something is really wrong here... I created an object of house and I'm still getting the error. No inheritance or anything at this point.

Could this be a problem with my compiler? I'm using Visual C++ 2010 Express.


EDIT:: Just tried it in Dev-C++, no dice. Same error.

Any suggestions?
Last edited on
Hi kultrva. Like jsmith said, protected members are only accesible from the class where they were defined and from classes derived from it. You only have to create a getter function member.

For example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class house{

protected:
	int coordinateX;
	int coordinateY;
	int coordinateZ;

public:
	void setCoordinates(int x, int y, int z){
		coordinateX = x;
		coordinateY = y;
		coordinateZ = z;
	}
        int getCoordinateX() const { return coordinateX; };
};

// Later...

int main(int argc, char** argv) {
   house myHouse;
   myHouse.setCoordinates(...);
   cout << myHouse.getCoordinateX();
   return 0;
}


Then you create an object of the class house, and finally call the function getCoordinateX().

I hope that helps you.
Last edited on
Thank you. That worked beautifully.
Topic archived. No new replies allowed.