The Wayback Machine - https://web.archive.org/web/20240930232000/https://www.geeksforgeeks.org/difference-c-structures-c-structures/
Open In App

Difference Between C Structures and C++ Structures

Last Updated : 25 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let’s discuss, what are the differences between structures in C and structures in C++? In C++, structures are similar to classes.

Differences Between the C and C++ Structures

C Structures

C++ Structures

Only data members are allowed, it cannot have member functions. Can hold both: member functions and data members.
Cannot have static members. Can have static members.
Cannot have a constructor inside a structure. Constructor creation is allowed.
Direct Initialization of data members is not possible. Direct Initialization of data members is possible.
Writing the ‘struct’ keyword is necessary to declare structure-type variables. Writing the ‘struct’ keyword is not necessary to declare structure-type variables.
Do not have access modifiers. Supports access modifiers.
Only pointers to structs are allowed. Can have both pointers and references to the struct.
Sizeof operator will generate 0  for an empty structure. Sizeof operator will generate 1 for an empty structure.
Data Hiding is not possible. Data Hiding is possible.

Similarities Between the C and C++ Structures

  • Both in C and C++, members of the structure have public visibility by default.

Lets discuss some of the above mentioned differences and similarities one by one:

1. Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.

C




// C Program to Implement Member
// functions inside structure
 
#include <stdio.h>
 
struct marks {
    int num;
 
    // Member function inside Structure to
    // take input and store it in "num"
    void Set(int temp) { num = temp; }
 
    // function used to display the values
    void display() { printf("%d", num); }
};
 
// Driver Program
int main()
{
    struct marks m1;
    // calling function inside Struct to
    // initialize value to num
    m1.Set(9);
 
    // calling function inside struct to
    // display value of Num
    m1.display();
}


Output

This will generate an error in C but no error in C++. 

C++




// C++ Program to Implement Member functions inside
// structure
 
#include <iostream>
using namespace std;
 
struct marks {
    int num;
 
    // Member function inside Structure to
    // take input and store it in "num"
    void Set(int temp) { num = temp; }
 
    // function used to display the values
    void display() { cout << "num=" << num; }
};
 
// Driver Program
int main()
{
    marks m1;
 
    // calling function inside Struct to
    // initialize value to num
    m1.Set(9);
 
    // calling function inside struct to
    // display value of Num
    m1.display();
}


 
 

Output

num=9

 

2. Static Members: C structures cannot have static members but are allowed in C++. 

 

C




// C program with structure static member
 
struct Record {
    static int x;
};
 
// Driver program
int main() { return 0; }


C++




// C++ program with structure static member
 
struct Record {
    static int x;
};
 
// Driver program
int main() { return 0; }


This will generate an error in C but not in C++. 

3. Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation.

C




// C program to demonstrate that
// Constructor is not allowed
 
#include <stdio.h>
 
struct Student {
    int roll;
    Student(int x) { roll = x; }
};
 
// Driver Program
int main()
{
    struct Student s(2);
    printf("%d", s.x);
    return 0;
}


C++




// 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;
}


This will generate an error in C.

Output in C++:

2

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

C




// C program to demonstrate that direct
// member initialization is not possible in C
 
#include <stdio.h>
 
struct Record {
    int x = 7;
};
 
// Driver Program
int main()
{
    struct Record s;
    printf("%d", s.x);
    return 0;
}


C++




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


This will generate an error in C.

Output in C++: 

7

5. Using struct keyword: In C, we need to use a struct to declare a struct variable. In C++, a struct is not necessary. For example, let there be a structure for Record. In C, we must use “struct Record” for Record variables. In C++, we need not use struct, and using ‘Record‘ only would work.

6. 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.  

7. Pointers and References: In C++, there can be both pointers and references to a struct in C++, but only pointers to structs are allowed in C. 

8. sizeof operator: This operator will generate 0 for an empty structure in C whereas 1 for an empty structure in C++.  

C




// C program to illustrate empty structure
 
#include <stdio.h>
 
// empty structure
struct Record {
};
 
// Driver Code
int main()
{
    struct Record s;
    printf("%lu\n", sizeof(s));
    return 0;
}


C++




// C++ program to illustrate empty structure
#include <iostream>
using namespace std;
 
// empty structure
struct Record {
};
 
// Driver program
int main()
{
    struct Record s;
    cout << sizeof(s);
    return 0;
}
 
// This code is contributed by Shubham Sharma


Output in C: 

0

Output in C++: 

1

NOTE:   The default type of  sizeof  is long unsigned int , that’s why  “%lu” is used instead of “%d” in printf function.

9. Data Hiding: C structures do not allow the concept of Data hiding but are permitted in C++ as it is an object-oriented language whereas C is not. 

10. Constant Members: C struct may allow to declare constant members, but no way to initialize. But in C++, you can initialize using constructor initializer list

C




#include <stdio.h>
 
struct C_struct
{
    const int i;
    int k;
};
int main()
{
    printf("Struct with constant members, but how to init??");
    return 0;
}


C++




#include <iostream>
using namespace std;
 
struct Cpp_Struct
{
  public:
    const int i;
    int k;
    Cpp_Struct():i(2),k(3){}
};
int main()
{
    Cpp_Struct obj1;
    cout << "Struct with constant members: " << obj1.i << " " << obj1.k << endl;
    return 0;
}


Output in C:

Struct with constant members, but how to init??

Output in C++:

Struct with constant members: 2 3

 
Related Article: Structure vs Class in C++
 



Previous Article
Next Article

Similar Reads

Difference between Linear and Non-linear Data Structures
Linear Data Structure: Data structure where data elements are arranged sequentially or linearly where each and every element is attached to its previous and next adjacent is called a linear data structure. In linear data structure, single level is involved. Therefore, we can traverse all the elements in single run only. Linear data structures are e
5 min read
Difference between Swift Structures and C Structure
Swift structures are a basic building block in the Swift programming language. They are used to group related data together in a single unit. They are similar to classes, but differ in several key ways, including: Value Types: Structures are value types, meaning that when you pass a structure to a function or assign it to a constant or variable, a
4 min read
Difference Between Homologous And Analogous Structures
The difference between Homologous and Analogous structures lies in their evolutionary origins and functional similarities. Homologous structures share a common evolutionary origin, indicating divergence from a common ancestor. In contrast, analogous structures serve similar functions but have different evolutionary origins. Understanding the differ
6 min read
Difference Between Stack and Queue Data Structures
In computer science, data structures are fundamental concepts that are crucial for organizing and storing data efficiently. Among the various data structures, stacks and queues are two of the most basic yet essential structures used in programming and algorithm design. Despite their simplicity, they form the backbone of many complex systems and app
4 min read
Internal Data Structures and Time Complexity Table of All the C++ STL Containers
As we all are using STL quite heavily in our programs in Interviews, Coding Contests. So knowing the Time complexity of the most frequently used operation and the data structure used behind the scene (in the internal implementation of the STL Library) is a must to know information. C++ STL Containers with Time Complexity & Data Structure used B
2 min read
Difference between Voltage Drop and Potential Difference
Voltage Drop is defined as the decrease in the electric potential along the path of current that is flowing in an electric circuit. Voltage drop can be assigned at each point in the electric circuit that is proportional to the electrical elevation. The amount of energy delivered per second to any component in the circuit is equal to the voltage dro
4 min read
Difference Between Electric Potential and Potential Difference
The flow of electric charges is known as electricity, and it is responsible for producing electric current. An important word associated with electricity is electric potential. A potential difference is required to create the flow of electrons and hence, produce electricity. Before understanding the difference between electric potential and potenti
7 min read
Difference between Difference Engine and Analytical Engine
The development of computing technology has a rich history, with many inventions and innovations leading to the creation of the modern computer. Two such machines, the Difference Engine and Analytical Engine, were created by the English mathematician and inventor Charles Babbage in the 19th century. While these machines share some similarities, the
7 min read
Policy based data structures in g++
The g++ compiler also supports some data structures that are not part of the C++ standard library. Such structures are called policy-based data structures. These data structures are designed for high-performance, flexibility, semantic safety, and conformance to the corresponding containers in std.To use these structures, the following lines must be
6 min read
Structures in C++
We often come around situations where we need to store a group of data whether of similar data types or non-similar data types. We have seen Arrays in C++ which are used to store set of data of similar data types at contiguous memory locations.Unlike Arrays, Structures in C++ are user defined data types which are used to store group of items of non
5 min read
Slack Bytes in Structures : Explained with Example
Structures: Structures are used to store the data belonging to different data types under the same variable name. An example of a structure is as shown below: struct STUDENT { char[10] name; int id; }; The memory space for the above structure would be allocated as shown below: Here we see that there is no empty spaces in between the members of the
3 min read
What are the C programming concepts used as Data Structures
Data Types Data-type in simple terms gives us information about the type of data. Example, integer, character, etc. Data-types in C language are declarations for the variables. Data-types are classified as: Primitive or Built-in data types Some of the examples of primitive data types are as follows Variable named ch refers to the memory address 100
10 min read
Array of Structures vs Array within a Structure in C
Both Array of Structures and Array within a Structure in C programming is a combination of arrays and structures but both are used to serve different purposes. Array within a Structure A structure is a data type in C that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain element
5 min read
Array of Structures vs Array within a Structure in C++
In C++, an array of structure and an array within structure are used frequently used for data storage. Although they sound similar, they work pretty differently from each other. In this article, we will discuss the key differences between an array of structures and an array within structures and clarify the confusion. Array of Structures in C++An a
4 min read
Time complexities of different data structures
Time Complexity is a concept in computer science that deals with the quantification of the amount of time taken by a set of code or algorithm to process or run as a function of the amount of input. In other words, the time complexity is how long a program takes to process a given input. The efficiency of an algorithm depends on two parameters: Time
2 min read
C Structures
The structure in C is a user-defined data type that can be used to group items of possibly different types into a single type. The struct keyword is used to define the structure in the C programming language. The items in the structure are called its member and they can be of any valid data type. Additionally, the values of a structure are stored i
10 min read
Difference and Similarities between PHP and C
PHP is a server-side scripting language designed specifically for web development. It can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP from a client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. C is a
3 min read
Similarities and Difference between Java and C++
Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as comepetitive programming . C++ is a widely popular language among coders for its efficiency, high speed, and dynamic memory utilization. Java is widely used in the
6 min read
Difference between Time Tracking and Time and Attendance Software
Time tracking and time and attendance software are tools that help businesses track the time that employees spend on tasks and their attendance records. These tools can help businesses automate their time tracking processes, reduce errors and inaccuracies, and ensure that employees are paid accurately for the time they work. Time tracking software
4 min read
Difference Between Single and Double Quotes in Shell Script and Linux
Single quotes and double quotes are both functional in Linux while working with shell scripts or executing commands directly in the terminal but there is a difference between the way the bash shell interprets them. Single quotes: Enclosing characters in single quotation marks (') holds onto the literal value of each character within the quotes. In
3 min read
Difference Between Monophyletic and vs Paraphyletic and vs Polyphyletic
In phylogeny, a taxon is a collection of organisms. Defining taxa makes it simpler to classify and identify creatures while also helping us to understand how they relate to one another. Based on these traits, taxa are developed. While some taxa are made up of unrelated creatures, others contain related species. Taxa classify descendants and ancesto
7 min read
Difference Between Grin And Smile And Smirk
Difference Between Grin And Smile And Smirk: Emotions are expressed by facial expressions. Facial expressions are considered an as important aspect of non-verbal communication. Facial expressions consist of various different body moments such as moving lips upward or downward, movement of raising the eyebrows, and giving the wide smile while descri
6 min read
Difference Between Store‑and‑Forward Switching and Cut‑Through Switching
Switching is a technique to transmit data between networks using switches that connect multiple LANs. Switches forward data packets based on MAC addresses, efficiently using bandwidth and reducing collisions. The three main types are: Circuit Switching: Dedicated path for the entire connection, used in traditional telephony.Message Switching: Entir
5 min read
Difference between Stop and Wait protocol and Sliding Window protocol
Both the Stop and Wait protocol and the Sliding Window protocol are the techniques to the solution of flow control handling. The main difference between the Stop-and-wait protocol and the Sliding window protocol is that in the Stop-and-Wait Protocol, the sender sends one frame and waits for acknowledgment from the receiver whereas in the sliding wi
5 min read
Difference between Black Box and White and Grey Box Testing
1. Black Box Testing : Black box testing is a type of software testing in which the functionality of the software is not known. The testing is done without the internal knowledge of the products. It is also called Functional testing. Black-box testing focuses on software’s external attributes and behavior. This type of testing looks at an applicati
4 min read
Difference between ++*p, *p++ and *++p
Predict the output of following C programs. C/C++ Code // PROGRAM 1 #include <stdio.h> int main(void) { int arr[] = {10, 20}; int *p = arr; ++*p; printf("arr[0] = %d, arr[1] = %d, *p = %d", arr[0], arr[1], *p); return 0; } C/C++ Code // PROGRAM 2 #include <stdio.h> int main(void) { int arr[] = {10, 20}; int *p = arr; *p++; pri
2 min read
Difference between sh and bash
bash and sh are two different shells of the Unix operating system. bash is sh, but with more features and better syntax. Bash is “Bourne Again SHell”, and is an improvement of the sh (original Bourne shell). Shell scripting is scripting in any shell, whereas Bash scripting is scripting specifically for Bash. sh is a shell command-line interpreter o
4 min read
Difference Between DOS and Windows
DOS: DOS stands for Disk Operating System, which is an operating system that was popular till 1995 in the IBM PCs. It is a single-tasking OS i.e., it can perform one task at a time. It is based on a command-line interface where we have to provide instruction to the computer in commands form. It runs from hard disks,floppy disk or any other storage
4 min read
What's difference between MMU and MPU?
Literally speaking, MMU is 'Memory Management Unit' while MPU is 'Memory Protection Unit'. Both of these are specialized hardware that is used by CPU for memory handling. MMU is used for many functions primarily Virtual Memory (i.e. translation of virtual address to physical address) and memory protection. But MPU is used for memory protection only
2 min read
What’s difference between “array” and “&array” for “int array[5]” ?
If someone has defined an array such as “int array[5]”, what’s the meaning of “array” or “&array”? Are they both same or are they different? You might be tempted to think that they both would point to the very first element of the array i.e. they both will have same address. Let us find out! To check this, the very first thing that comes to min
4 min read
Practice Tags :