In C++, a structure is same as class except the following differences:
1) Members of a class are private by default and members of struct are public by default.
For example program 1 fails in compilation and program 2 works fine.
// Program 1 #include <stdio.h> class Test { int x; // x is private }; int main() { Test t; t.x = 20; // compiler error because x is private getchar(); return 0; } |
chevron_right
filter_none
// Program 2 #include <stdio.h> struct Test { int x; // x is public }; int main() { Test t; t.x = 20; // works fine because x is public getchar(); return 0; } |
chevron_right
filter_none
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 <stdio.h> 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 getchar(); return 0; } |
chevron_right
filter_none
// Program 4 #include <stdio.h> 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 getchar(); return 0; } |
chevron_right
filter_none
Related Article: Difference between C structures and C++ structures
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- STL Priority Queue for Structure or Class
- Difference between Abstract Class and Concrete Class in Java
- Fork CPP | Course Structure
- Difference between Structure and Union in C
- Structure Sorting (By Multiple Rules) in C++
- std::any Class in C++
- std:: valarray class in C++
- Array class in C++
- std::string class in C++
- C++ String Class and its Applications | Set 2
- Difference between namespace and class
- C++ string class and its applications
- Friend class and function in C++
- What all is inherited from parent class in C++?
- Can a C++ class have an object of self type?



