Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting access to derived class for a pure virtual function in c++

Tags:

c++

virtual

class A
{    
public:
    void virtual magic() = 0;
    void bar()
    {
        magic();    // this should be legal
    }        
};

class B: public A
{    
public:
    void magic()
    {
        cout<<"implement magic here"<<endl;
    }
};

class C: public B
{
     void foo()
     {
         magic();     // this should not be allowed, i.e. create compile-time error
     }
};

Thus the pure virtual base class A of B shall have access to magic(), but not any derived class C of B. Can this be achieved using access specifiers and/or friend declarations or in any other way?

like image 528
Chris Avatar asked Dec 11 '22 11:12

Chris


1 Answers

Basically, you cannot reduce the visibility of a virtual method. Once it's public in A, there's no tidy way to make it protected or private in any of the derived classes.

like image 83
NPE Avatar answered Dec 13 '22 23:12

NPE