[C++] What are the differences between classes and structs?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Thread: [C++] What are the differences between classes and structs?

Threaded View

  1. #1
    Join Date
    Nov 2006
    Location
    Australia
    Posts
    1,569

    [C++] What are the differences between classes and structs?

    Q: What are the differences between classes and structures in C++?

    A:
    • Classes have private members by default, whereas structures have public members by default:
      Code:
      class CFoo
      {
        void f() {}
      };
      
      struct SFoo
      {
        void f() {}
      };
      
      int main()
      {
        Cfoo c;
        c.f(); // error: 'CFoo::f' : cannot access private member declared in class 'CFoo'
      
        SFoo s;
        s.f(); // OK
      
        return 0;
      }
    • Classes have private inheritance by default, whereas structures have public inheritance by default:
      Code:
      class CBase
      {
      public:
        void f() {}
      };
      
      struct SBase
      {
      public:
        void f() {}
      };
      
      class CFoo : CBase
      {
      };
      
      struct SFoo : SBase
      {
      };
      
      int main()
      {
        CFoo c;
        c.f(); // error: 'CBase::f' not accessible because 'CFoo' uses 'private' to inherit from 'CBase'
      
        SFoo s;
        s.f(); // OK
      
        return 0;
      }
    Last edited by cilu; May 27th, 2008 at 01:45 PM. Reason: renamed entities
    Good judgment is gained from experience. Experience is gained from bad judgment.
    Cosy Little Game | SDL | GM script | VLD | Syntax Hlt | Can you help me with my homework assignment?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center