C++ Tutorial
Class and Object
Reference
Inheritance and Derivation
Polymorphism and Virtual Functions
Operator Overloading
Template
Exception
Object Oriented Advanced
Input/Output Stream
File Operations
In C++, both classes and structs are used to create user-defined data types that can hold data members (variables) and member functions (methods). However, there are some differences between classes and structs in terms of default access specifiers and inheritance.
The main difference between a class and a struct in C++ is the default access specifier for their members. In a class, the default access specifier is private
, while in a struct, it is public
.
For example, consider the following class and struct:
class MyClass { int x; // This is private by default public: int y; }; struct MyStruct { int x; // This is public by default int y; };
In this example, x
is a private member of MyClass
, while it is a public member of MyStruct
. y
is a public member in both cases.
When it comes to inheritance, classes and structs also have different default access specifiers. In a class, the default inheritance is private
, while in a struct, it is public
.
For example, consider the following class and struct:
class Base { public: int x; }; class Derived1 : Base { // Inherits privately by default // x is now private in Derived1 }; struct Derived2 : Base { // Inherits publicly by default // x is now public in Derived2 };
In this example, Derived1
privately inherits from Base
, so x
is private in Derived1
. Derived2
publicly inherits from Base
, so x
is public in Derived2
.
Apart from these differences, classes and structs in C++ are almost identical. You can use constructors, destructors, member functions, and other features with both classes and structs.
It is a common practice to use structs for simple data structures with public data members and no member functions, while classes are used for more complex data structures with encapsulation and member functions. However, this is more of a convention than a strict rule, and you can use either one based on your specific use case and programming style.
C++ class vs struct differences:
// C++ class class MyClass { private: int privateMember; public: int publicMember; }; // C++ struct struct MyStruct { int publicMember; };