
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
C/C++ Struct vs Class
In C++ the structure and class are basically same. But there are some minor differences. These differences are like below.
The class members are private by default, but members of structures are public. Let us see these two codes to see the differences.
Example
#include <iostream> using namespace std; class my_class { int x = 10; }; int main() { my_class my_ob; cout << my_ob.x; }
Output
This program will not be compiled. It will generate compile time error for the private data member.
Example
#include <iostream> using namespace std; struct my_struct { int x = 10; }; int main() { my_struct my_ob; cout << my_ob.x; }
Output
10
When we derive a structure from a class or structure, the default access specifier of that base class is public, but when we deriving a class the default access specifier is private.
Example
#include <iostream> using namespace std; class my_base_class { public: int x = 10; }; class my_derived_class : my_base_class { }; int main() { my_derived_class d; cout << d.x; }
Output
This program will not be compiled. It will generate compile time error that the variable x of the base class is inaccessible
Example
#include <iostream> using namespace std; class my_base_class { public: int x = 10; }; struct my_derived_struct : my_base_class { }; int main() { my_derived_struct d; cout << d.x; }
Output
10
- Related Articles
- When should you use a class vs a struct in C++?
- What are the differences between struct and class in C++?
- Debug Class vs Debugger Class in C#
- Structure vs class in C++
- What are the differences between a class and struct in C#?
- Abstract vs Sealed Classes vs Class Members in C#
- C# Int16 Struct
- C# Int32 Struct
- How to create an unordered_set of user defined class or struct in C++?
- UInt16 Struct in C#
- UInt32 Struct in C#
- UInt64 Struct in C#
- Decimal Struct in C#
- Char Struct in C#
- Byte Struct in C#

Advertisements