vendredi 5 avril 2019

Why doesn't a class having private constructor prevent inheriting from this class? How to control which classes can inherit from a certain base?

class B {
private:
    friend class C;
    B() = default;
};

class C : public B {};
class D : public B {};

int main() {
    C {};
    D {};
    return 0;
}

I assumed that since only class C is a friend of B, and B's constructor is private, then only class C is valid and D is not allowed to instantiate B. But that's not how it works. Where am I wrong with my reasoning, and how to achieve this kind of control over which classes are allowed to sublcass a certain base?

Aucun commentaire:

Enregistrer un commentaire