Till now we have seen everything about classes. Now we shall see in-depth on C++ Structures.
In this chapter we shall learn about below topics in C++:
1. Structure Introduction
2. How to define a structure?
3. How to create structure variable?
4. Example for a structure with constructor, member function and data member.
5. Difference between C structures and C++ Structures
C++ structure is almost similar to C++ classes, the only difference being, if you don’t specify any access specifiers, the default will be public. Rest all will remain the same.
1. Structure Introduction:
- “struct” is the keyword used to declare a structure in C++.
- C++ structure can have data member and member functions.
- You can create structure variable, just like you create objects for the class.
- Constructor and destructor are also present in structure.
- You can access by dot “.” Operator or using arrow “->” operator.
2. How to define a structure?
struct MyStruct { int num; MyStruct() { num = 10; } void dispaly() { cout<<"In structure the num value is "<< num<<endl; } };
Remember to close the end of the structure using semi colon.
3. How to create structure variable?
Method 1:
Create the variable while creating a structure:
struct MyStruct { int num; }str_obj;
Method 2:
Create them as you create a normal variable.
MyStruct str_obj;
4. How to access members of structure?
You can access structure members, you need to access using dot “.” Operator.
Example:
Str_obj.num = 10;
5. Example for a structure with constructor, member function and data member.
#include <iostream> using namespace std; struct MyStruct { //data member int num; //constructor MyStruct(int b) { num = b; } //member function void display() { cout<<"The num value is "<<num<<endl; } }; int main(void) { MyStruct obj (10); obj.display(); return 0; }
Output:
The num value is 10
6. Difference between C++ Structure and C++ Classes
The only difference between C++ classes and C++ structure is, by default all the all structure members are by default public access specifier.
Difference between C structures and C++ Structures
- You cannot declare a member function in C structure.
- You cannot directly initialize data member in C, but you can do it in C++.
struct MyStruct { int num = 10; };
The above statement is valid in C++, but not in C.
- While creating structure variables in C, you need to put “struct” keyword. But not in C++.
In C “struct MyStruct obj;” In C++ “MyStruct obj;”
- C structure cannot have static variable. C++ structure can have a static variable.
- C structure cannot have constructor and C++ structure can have a constructor.
- Size of empty structure is 0, but in C++ it is 1.
#include <iostream> using namespace std; struct MyStruct { }; int main(void) { MyStruct obj; cout<<"size is "<<sizeof(obj); return 0; }
Output:
size is 1