1 of 9

Difference between C structures and C++ structures�

2 of 9

1. Member functions inside structure

  • Structures in C cannot have member functions inside structure

  • but Structures in C++ can have member functions along with data members.

3 of 9

2. Direct Initialization: �We cannot directly initialize structure data members in C but we can do it in C++.

  • Code in C++
  • #include <iostream>
  • using namespace std;
  •   
  • struct Record {
  •     int x = 7;
  • };
  •   
  • // Driver Program
  • int main()
  • {
  •     Record s;
  •     cout << s.x << endl;
  •     return 0;
  • }

  • Code in C

  • struct Record {
  •     int x = 7;
  • };
  •   
  • int main()
  • {
  •     struct Record s;
  •     printf("%d", s.x);
  •     return 0;
  • }

4 of 9

3. Using struct keyword

  • In C, we need to use struct to declare a struct variable.

  • In C++, struct is not necessary.

5 of 9

4. Static Members

  • C structures cannot have static members but is allowed in C++.
  • // C program with structure static member
  • struct Record {
  •     static int x;
  • };

  • int main()
  • {
  •     return 0;
  • }
  • This will generate an error in C but no error in C++.

6 of 9

5. Constructor creation in structure

  • Structures in C cannot have constructor inside structure

  • but Structures in C++ can have Constructor creation.

                  • PTO

7 of 9

  • // C program to demonstrate that Constructor is not allowed
  • #include <stdio.h>

  • struct Student {
  •     int roll;
  •     Student(int x)
  •     {
  •         roll = x;
  •     }
  • };
  •   
  • int main()
  • {
  •     struct Student s(2);
  •     printf("%d", s.x);
  •     return 0;
  • }
  • /* Output :  Compiler Error

  • // CPP program to initialize data member in c++
  • #include <iostream>
  • using namespace std;
  •   
  • struct Student {
  •     int roll;
  •     Student(int x)
  •     {
  •         roll = x;
  •     }
  • };
  •   
  • // Driver Program
  • int main()
  • {
  •     struct Student s(2);
  •     cout << s.roll;
  •     return 0;
  • }
  • // Output
  • // 2

8 of 9

6. Data Hiding

  • C structures do not allow concept of Data hiding .

  • but is permitted in C++ as C++ is an object oriented language whereas C is not.

9 of 9

7. Access Modifiers

  • C structures do not have access modifiers as these modifiers are not supported by the language.

  • C++ structures can have this concept as it is inbuilt in the language.