Reputation: 115
class A
{
//friend class B;
protected:
A(){cout << "A\n";};
};
class B: virtual A
{};
class C : B
{};
int main() {
C c;
return 0;
}
I am able to compile this code successfully though I was expecting error due to A:A() is protected. Basing on the fact that for virtual base class its most derived class calls it base class directly. The above code gives compile error[expected] for private access to ctor() in base class. Can someone please clarify this, Thanks!
Upvotes: 2
Views: 75
Reputation: 170084
Having a protected
access specifier means that derived classed may access the entity. C
is also derived from A
, it doesn't have to be directly derived from it to qualify for protected access.
On the other hand, private
access will prevent any derived class from having accessibility, both B
and C
.
There is no way to control access in a way that will only allow directly derived classed to access the constructor (specifically, an open set of directly derived classes). The most you can do is to play with private
access and friend
ship with a closed set of derived classes.
To address your comment on your question:
I want to forbid inheritance from B
Just mark B
as final
class B final : A
{};
Upvotes: 3