why C++ has both struct and class????

C++ is a super-set of C language...C language has struct ( structures ) while C++ has struct and class ( ADT's).....by default the access specifier of struct is public and class access specifier is private.... my question is why C++ has both of them ( struct and class )....and also tell me what are the main differences between struct and class?????? thanks to seniors ......
C++ is, as you state, to a large extent a super-set of C (not quite exactly, but very nearly). C has structs, so they must be compatible with C++, so we've got struct. In C++, however, structs can have additional things (methods, privacy levels, inheritance). C++ has both to maintain compatibility with C.

As you stated, the difference between a class and a struct in C++ is the default privacy level. A stuct's members are default public; a class' members are default private. This carries into inheritance as well.

This is the only difference between struct and class in C++. You can use a struct like a class, and a class like a struct.
Last edited on
two more things makes struct differs from class:
struct object may be declared with struct keyword:
struct Object x; //C stile where Object is an struct name and x is an object

second thing is that struct may be initialized when declared:
struct Object x = { "some char", 99, 'm', "etc..." };

two more things makes struct differs from class:


Classes do the exact same thing, as in the code below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>
#include <iostream>

class Object
{
public:
  std::string a;
  int b;
  char c;
  std::string d;
};

int main()
{

class Object x = { "some char", 99, 'm', "etc..." };

 std::cout << x.a << " " << x.b << " " << x.c << " " << x.d;
 return 0;
}

thanks ... i also find .... the things that i can do with struct ....do also the same thing using class....

Moschops..... can u explain further these two lines.....

(1) C++ has both to maintain compatibility with C..... compatibility in what sense???

(2) This carries into inheritance as well....


thanks..:)
compatibility in what sense???


Almost all C code is also C++ code. This means something that is a correct struct in C should also be a correct struct in C++.

(2) This carries into inheritance as well....


Default public/private inheritance depends on whether the object is a class or a struct.
Last edited on
Classes do the exact same thing, as in the code below.

I didn't know that lol :D
Topic archived. No new replies allowed.