7.3: Structures in C++ (cont'd)
- Page ID
- 34673
2) When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.
For example program 3 fails in compilation and program 4 works fine.
// Program 3
#include <iostream>
using namespace.std;
class Base {
public:
int x;
};
class Derived : Base { }; // is equilalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error becuase inheritance is private
return 0;
}
So...if we use a struct instead of class we get a different result
// Program 4
#include <iostream>
using namespace std;
class Base {
public:
int x;
};
struct Derived : Base { }; // is equilalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // works fine becuase inheritance is public
return 0;
}
Adapted from:
"Structure vs class in C++" by roopkatha, Geeks for Geeks is licensed under CC BY-SA 4.0