0

I have an interface in C++ that looks something like this:

// A.h
#pragma once

class A
{
public:
    //Some declarations.    
private:    
    //Some declarations.
protected:
    //Some declarations.
};

The specific form is not important. Since this is an interface, there will be a class B that inherits from A. In the header file for class B I have:

// B.h
#pragma once

class B : A
{
public:
    //Some declarations.    
private:    
    //Some declarations.
protected:
    //Some declarations.
};

My concern is that I tend to use class B : A instead of class B : public A, just my bad memory.

So far I have had no issues with this, since it's a small enough project. But will forgetting the public keyword affect my project in any sense?

Or more succinctly, I know how access modifiers work but, what does class B : A default to?

anastaciu
  • 22,293
  • 7
  • 26
  • 44
  • Duplicate? https://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance –  Mar 12 '21 at 17:06
  • Hi, I already took a look at that, it does not address the default modifier. –  Mar 12 '21 at 17:08
  • It doesn't? `class D : private A // 'private' is default for classes` –  Mar 12 '21 at 17:09
  • 1
    Might have overseen it, sorry. Thank you. –  Mar 12 '21 at 17:16

2 Answers2

2

What does class B : A default to?

class B : private A { /*...*/ }

But will forgetting the public keyword affect my project in any sense?

Yes. Don't forget it.

Consider the following:

// A.h
class A {

public:
   void f(){}  
};

// B.h
class B : A {};

int main() {

   B b;
   b.f(); // f is inaccessible because of private inheritance
}
anastaciu
  • 22,293
  • 7
  • 26
  • 44
1

The ONLY difference between struct and class is that in a struct, everything is public until declared otherwise, and in a class, everything is private until declared otherwise. That includes inheritance. So class B : A will default to private inheritance, and struct B : A will default to public inheritance.

Mooing Duck
  • 59,144
  • 17
  • 92
  • 149
  • @rustyx Sure, but answering the question as asked without mentioning that `struct` works the opposite way would have been misleading. – Mooing Duck Mar 12 '21 at 17:33