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++:
Structure Introduction:
How to define a structure?
How to create structure variable?
Example for a structure with constructor, member function and data member.
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.
Structure Introduction:
1. “struct” is the keyword used to declare a structure in C++.
2. C++ structure can have data member and member functions.
3. You can create structure variable, just like you create objects for the class.
4. Constructor and destructor are also present in structure.
5. You can access by dot “.” Operator or using arrow “->” operator.
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.
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;
How to access members of structure?
You can access structure members, you need to access using dot “.” Operator.
Example:
Str_obj.num = 10;
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
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
1. You cannot declare a member function in C structure.
2. 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.
3. 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;”
4. C structure cannot have static variable. C++ structure can have a static variable.
5. C structure cannot have constructor and C++ structure can have a constructor.
6. 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