protected inheritance, Compiler Error C2243

hello
I have a base class and a child class, my base class has a public test function and child class inherits base class as protected, because I dont want any of base class functionalities to be accessible from outside of the class. However, when I try to use polymorphism my compiler gives this error:

'conversion type' conversion from 'type1' to 'type2' exists, but is inaccessible

Access protection (protected or private) prevented conversion from a pointer to a derived class to a pointer to the base class.

what should I do ?
(by the way I dont want to inherit base class as public, it should be protected)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class base
{
public:
	base(){}
	void test()
	{
		cout<<"test"<<endl;
	}
};
class child : protected base
{
};
int main()
{
	base* a = new child();
	a->test();
}


an other question,

I want my inherited class to have some of base class functions and properties, but I also want some of base functions and properties not to be inherited, I dont know how to do that.

thank you for your replies, and I am sorry for my bad English
I think it might be that since you specified the child class as protected (minimum level of protection), it is making the base() protected, which makes it unable to convert the types...(although again, I am not completely sure on this, I'm probably wrong).

You cannot selectively inherit things from certain classes. If you need to do that, you need to rethink you design and possibly change your inheritance model, i.e. if you want class 'b' to only inhert some stuff from class 'a', you should create a class 's' that contains only the things 'a' and 'b' have in common then have 'a' and 'b' inherit from 's'.
If you want to change the access specifier for child::test(), I think you can add these lines to the child class:
1
2
public:
    base::test();  // now child::test() is public, and it just calls base::test() 


I haven't tried it but I think this will work.

Now, the real question is why use protected inheritance? I read your explanation above, and I need it to be a little more specific. From your description, I think you might have meant to declare base::test() protected and use public inheritance. That would make base::test() available for use in child; but not outside of either class (unless you override the access specifier as I suggested above).

Generally, protected/private inheritance is used for inheriting implementation. Public inheritance is used for inheriting interfaces (note the "is a" relationship should always hold). To determine appropriate access specifiers inside a class, you have to consider 2 interfaces: one to the user of the class and one to the child class.

So, explain what exactly you want to be accessible and not accessible and we can be much more helpful.
Last edited on
Topic archived. No new replies allowed.