What is the difference between Class and structure

Recommended Answers

All 2 Replies

classes are declared using the keyword class while structures are declared using the keyword struct

structures are entirely public, while classes are private by default

The only real difference between a struct and a class is in the default inheritance and access rights. Given a base-class B, you could write:

class C : B {  // inherits B privately, by default, same as ': private B {'.
  void foo();  // private member function, same as 'private: void foo();'.
};

struct D : B {  // inherits B publicly, by default, same as ': public B {'.
  void foo();   // public member function, same as 'public: void foo();'.
};

Generally, it is not recommended to use the default inheritance or access rights, so you should always spell it out (i.e., have the public or private keywords explicitly stated). With regards to the C++ Standard, there is never any distinction made between a struct or a class (except where it specifies the default rights associated to them), they are both referred to as a class.

In common coding practice and popular terminology, C++ programmers will often say a "structure" for something ressembling a C-style struct (meaning a struct that would be valid in C: no inheritance, only public data members, and no member functions). In formal language (as in the ISO standard document), this is called a POD-type (Plain-Old-Data type). Often, C++ programmers will use the keyword struct when building such a simple class (just a container of a few data members, with only simple and public member functions). But this is nothing more than a convention (and a bit of syntax convenience as POD-types usually only contain public members).

commented: nice information +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.