After creating an object, we can access the data and functions using the dot operator as shown below:
object-name.variable-name; (or)
object-name.function-name(params-list);
Based on our student class example, we can access the get_details() function as shown below:
std1.get_details();
std2.get_details();
The complete program which demonstrates creating class, creating objects, and accessing object members is as follows:
|
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
|
#include<iostream>
using namespace std;
class Student
{
private:
string name;
string regdno;
string branch;
int age;
public:
void get_details();
void show_details();
};
void Student::get_details()
{
cout<<“Enter student name: “;
cin>>name;
cout<<“Enter student regdno: “;
cin>>regdno;
cout<<“Enter student branch: “;
cin>>branch;
cout<<“Enter student age: “;
cin>>age;
}
void Student::show_details()
{
cout<<“—–Student Details—–“<<endl;
cout<<“Student name: “<<name<<endl;
cout<<“Student regdno: “<<regdno<<endl;
cout<<“Student branch: “<<branch<<endl;
cout<<“Student age: “<<age<<endl;
}
int main()
{
Student std1, std2;
std1.get_details();
std1.show_details();
return 0;
}
Input and output for the above program are as follows:
Enter student name: teja
Enter student regdno: 15pa1a0501
Enter student branch: teja
Enter student age: 22
——–Student Details——–
Student name: teja
Student regdno: 15pa1a0501
Student branch: teja
Student age: 22
|
In the above program class name is Student and object names are std1 and std2.
Nested Functions
A member function can call another member function directly without any need of dot operator. To call another member function, we can simply write the function name followed by parameter values enclosed in parentheses. An example for calling another member function is as follows:
|
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
|
#include<iostream>
using namespace std;
class Square
{
public:
int side;
public:
float area(float);
float peri(float);
void show_details();
};
float Square::area(float s)
{
return s*s;
}
float Square::peri(float s)
{
return 4*s;
}
void Square::show_details()
{
cout<<“Side is: “<<side<<endl;
cout<<“Area of sqaure is: “<<area(side)<<endl;
cout<<“Perimeter of sqaure is: “<<peri(side)<<endl;
}
int main()
{
Square s1;
s1.side = 2;
s1.show_details();
return 0;
}
Input and output for the above program is as follows:
Side is: 2
Area of sqaure is: 4
Perimeter of sqaure is: 8
|
In the above program, the function show_details() contains nested call to area() and peri() functions.
Take your time to comment on this article.