Home > Backend Development > C++ > body text

The difference between C/C++ structures and classes

PHPz
Release: 2023-09-17 18:13:02
forward
1339 people have browsed it

C/C++ 结构体与类的区别

In C, structures and classes are basically the same. But there are some subtle differences. These differences are shown below.

  • By default, class members are private, but structure members are public. Let's take a look at these two codes and see what's the difference.

Example

#include <iostream>
using namespace std;
class my_class {
   int x = 10;
};
int main() {
   my_class my_ob;
   cout << my_ob.x;
}
Copy after login

Output

This program will not be compiled. It will generate compile time error for
the private data member.
Copy after login

Example

#include <iostream>
using namespace std;
struct my_struct {
   int x = 10;
};
int main() {
   my_struct my_ob;
   cout << my_ob.x;
}
Copy after login

Output

10
Copy after login
Copy after login
  • When we derive a structure from a class or structure, the default access specifier of that base class is public, but when we deriving a class the default access specifier is private.

Example

#include <iostream>
using namespace std;
class my_base_class {
   public:
   int x = 10;
};
class my_derived_class : my_base_class {
};
int main() {
   my_derived_class d;
   cout << d.x;
}
Copy after login

Output

This program will not be compiled. It will generate compile time error that the variable x of the base class is inaccessible
Copy after login

Example

#include <iostream>
using namespace std;
class my_base_class {
   public:
   int x = 10;
};
struct my_derived_struct : my_base_class {
};
int main() {
   my_derived_struct d;
   cout << d.x;
}
Copy after login

Output

10
Copy after login
Copy after login

The above is the detailed content of The difference between C/C++ structures and classes. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template