Home > database >  Is it possible to have restricted access to included class?
Is it possible to have restricted access to included class?

Time:09-18

I have a class say A in A.h file and class B: public A in B.h file.

A.h file

#ifndef A_H
#define A_H

class A
{
  public:
    void foo {}
};

#endif

B.h file

#ifndef B_H
#define B_H
#include "A.h"

class B: public A
{
  ...
};

#endif 

Is there a way to include B but not to have access to A until I include A.h?

Like this

#include "B.h"

main() {
  B* b = new B(); //OK
  b->foo();       //OK
  A* a = new A(); //Error
  a->foo();       //Error  
}

CodePudding user response:

No. B.h depends on the definition of A, so there is no way to include B.h without including the definition of A. And there is no way of getting around that dependency if B must be defined in B.h and if B must inherit A.

You can make the creation of separate A into an error by changing A to be an abstract type. But that would remain an error even if A.h was included separately.

  • Related