0

I was wondering what the difference between the two.

Source: https://www.geeksforgeeks.org/array-of-structures-vs-array-within-a-structure-in-c-and-cpp/

Sample Array of Structure

#include <stdio.h>

struct class {
    int roll_no;
    char grade;
    float marks;
};

void display(struct class class_record[3])
{
    int i, len = 3;

    for (i = 0; i < len; i++) {
        printf("Roll number : %d\n",
            class_record[i].roll_no);
        printf("Grade : %c\n",
            class_record[i].grade);
        printf("Average marks : %.2f\n",
            class_record[i].marks);
        printf("\n");
    }
}

int main()
{
    struct class class_record[3]
        = { { 1, 'A', 89.5f },
            { 2, 'C', 67.5f },
            { 3, 'B', 70.5f } };

    display(class_record);
    return 0;
}
Its_Me
  • 55
  • 3
  • 7

1 Answers1

1

There is no difference between a class type and a structure type in C++. They are the same thing.

The code you are showing is C and not valid C++. In C++ class is a keyword and can not be used to name a type.

You create an array of a class type in C++ exactly in the same way as you create an array of any other type:

class C { }; // or identically struct instead of class

C c[123];

Here c is an array of 123 C objects.

user17732522
  • 53,019
  • 2
  • 56
  • 105
  • Okay thank you for the clarification, thats why I wonder I cannot run my program since it is in C style. – Its_Me Feb 20 '22 at 01:28
  • 1
    @Its_Me Don't learn C++ from C examples or tutorials and the linked website is known to be wrong about C++. Better get yourself [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – user17732522 Feb 20 '22 at 01:30
  • 1
    there is one difference. class members are private by default, struct members are public. This is done because the general expectation is that a class is used for encapsulation whereas a struct is used for data structures (just like c) – pm100 Feb 20 '22 at 01:31
  • 1
    @pm100 Yes. I specifically avoided that by talking only about the properties of the types, not the definitions. I think it is important to understand that "class type" is not somehow something different from "structure type". There are simply two keywords to define class types with different default access specifiers, but e.g. `struct A;` and `class A;` declare the same type. – user17732522 Feb 20 '22 at 01:33