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?

Jason
  • 36,170
  • 5
  • 26
  • 60

2 Answers2

3

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
  • 64,318
  • 19
  • 100
  • 158
  • @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
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
  • 23,467
  • 7
  • 28
  • 53