-
Notifications
You must be signed in to change notification settings - Fork 7
/
structure.cpp
92 lines (73 loc) · 2.24 KB
/
structure.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include<bits/stdc++.h>
using namespace std;
struct Point {
int x = 1; // Can initialize with some value in C++ but not in C
int y = 1;
} p1;
struct Employee {
private:
int eID;
string name;
int age;
public:
// Structs can also have constructors
Employee() {
eID = 0;
name = "";
age = 0;
}
void getInputData() {
cout << "Enter Employee ID, Employee name & Employee age: ";
/*
No Need of '.' operator to access member variables. (It will actually give CE)
This (->) pointer can be used but no need as such
*/
cin >> eID >> this->name >> age;
}
void printData(); // You can also define functions outside the struct
};
void Employee::printData() {
cout << "Hello " << name << ". Your Employee ID is " << eID << " and your age is " << age << endl;
}
int main() {
/*
What is structure?
--> Collection of dissimilar elements
--> Way to group variables
--> Used to create user-defined Data Type
--> Memory is only assigned when structure variable is declared and not when struct is defined
IMP: Writing the keyword struct before declaring a new structure variable is optional in C++
but mandatory in C
Some ways to create and initialize structure variable -->
Example struct:
struct myStruct(){
// member variables
} type1; ** First Type **
myStrcut type2={initialize here}; ** Second Type **
myStrcut type3; ** Third Type **
type3={initialize here}
myStrcut type4;
type4.someMemberVariable=someValue (Use of '.' operator) ** Fourth Type **
myStruct type5;
type5=type3 (Initialize with any other struct variable directly) ** Fifth Type **
*/
Point p2 = {2, 3};
Point p3;
p3 = {4, 5};
Point p4;
p4.x = 6, p4.y = 7;
/*
In C, structs could not have member functions but they can have in C++.
This is the beginning step to achieve encapsulation
(See Struct Employee)
IMP:
1. Struct can also have access specifiers public, private and protected
(See Employee struct)
For Difference between classes and structs see clasesAndObjects.cpp file
*/
Employee e1;
e1.getInputData();
e1.printData();
Employee e2;
e2.printData(); // Values set in constructor will get printed
}