Access check

Hello ,
I can't explain why I can access these functions .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;
class ACShape
{
public:
	virtual float get_area() const = 0;
	virtual ~ACShape() {};

	void set_meas(float w_,float l_)
	{
		width_ = w_;
		length_= l_;
	}

	void show()
	{
		cout << "hi";
	}

protected:
	float width_;
	float length_;
};

class Rectangle : public ACShape
{
private: 
	virtual float get_area() const
	{
		return width_ * length_;
	}
};

class Triangle : public ACShape
{
private:
	virtual float get_area() const
	{
		return 0.5f * width_ * length_;
	}
};

int main()
{
	{
		ACShape *shape [2] = { new Rectangle, new Triangle};

		shape[0]->set_meas(10.f,10.f);
		shape[1]->set_meas(10.f,10.f);

		cout << shape[0]->get_area() << endl;
		cout << shape[1]->get_area() << endl;
		shape[1]->show();

	}



	return 0;
}
Last edited on
Because those function are public in Shape.
could you explain me a little bit more detailed how the compiler checks the access fields( public, private, protected) ?
It seems pretty simple to me: public access methods can be called freely like you are doing. What part are you confused about? I'm not certain what you mean by "how the compiler checks the access fields".
I'm confused about the part that they are overridden in the private field of Rectangle,Triangle
Why should I be able to call them ?

My vague idea was that the compiler checks the public,protected,private fields at compile time so it still has my functions in the public area .
Last edited on
compiler checks the public,protected,private fields at compile time
Yes, this is part of the answer.

You never call any functions from Rectangle and Triangle. What you do is calling functions of Shape, which gives control to different code parts depending on whatever dynamic dispatch mechanism is used. It does not know which or how many derived classes there is and what bad decisions they made, and does not care: you are working with Shape.

You should not change access specifiers in derived classes.
http://www.parashift.com/c++-faq-lite/hiding-inherited-public.html
http://stackoverflow.com/questions/484592/overriding-public-virtual-functions-with-private-functions-in-c
thank you :)
Topic archived. No new replies allowed.