Skip to main content
Engineering LibreTexts

7.2: Structures in C++

  • Page ID
    34672
  • In C++, a structure is the same as a class except for a few differences. The most important of them is security. A Structure is not secure and cannot hide its implementation details from the end user while a class is secure and can hide its programming and designing details. Following are the points that expound on this difference:

    1) Members of a class are private by default and members of a struct are public by default.
    For example program 1 fails in compilation and program 2 works fine.

     
     
    // Program 1 
    #include <iostream>
    using namespace std 
    
    class Test { 
        int x; // x is private 
    }; 
    
    int main() 
    { 
       Test t;
    
       t.x = 20; // compiler error because x is private 
       return 0; 
    }
    BUT...if we use a struct instead of class we get a different result
     
    // Program 2
    #include<iostream>
    using namespace std;
    
    struct Test {
       int x; // x is public
    };
    
    int main()
    {
       Test t;
       t.x = 20; // works fine because x is public
       return 0;
    }
     

    Adapted from:
    "Structure vs class in C++" by roopkathaGeeks for Geeks is licensed under CC BY-SA 4.0  

    • Was this article helpful?