One question about protected constructor. I learnt that the protected constructor can be used in the derived class. How ever, I found the code below has an error. Why does it happen like this?
class A
{
protected:
A(){}
};
class B: public A {
public:
B() {
A* f=new A(); // Why it is not working here
}
};
This has nothing to do with constructors specifically. This is just how
protectedaccess works.The way
protectedaccess specifier works, it allows the derived classBto access the contents of an object of base classAonly when that object of classAis a subobject of classB. That means that the only thing you can do in your code is to access the contents ofAthroughB: you can access the members ofAthrough a pointer of typeB *(or a reference of typeB &). But you cannot access the same members through a pointer of typeA *(or referenceA &).Consider the following example
In the above
B::foo, you can access base memberA::iby using just plainisyntax. This is equivalent to usingthis->isyntax. Both will work, because the pointerthishas typeB *, i.e. you are accessingA::ithorough a pointer of typeB *. This is exactly what theprotectedaccess specifier is supposed to allow. The access throughpbpointer works for the very same reason.However, when you “convert”
thispointer to typeA *, you can no longer accessA::ithrough that new pointer, even though you are still trying to access they very same member as before.When applied to constructors, the
protectedaccess specifier has a very specific effect: a protected constructor can only be used to initialize base-class subobjects. It cannot be used to initialize standalone objects (which is what you were trying to do). In other words, protected constructors are another way to implement the concept of abstract class in C++ (along with pure virtual methods). If the constructors of your class are protected, then your class is effectively abstract. You can’t use it to define independent objects “from outside”. (Of course, the above does not apply within friends, as well as within the class itself).