Pointers can be used inside a class for the following reasons:
- Pointers save memory consumed by objects of a class.
- Pointers can be used to allocate memory dynamically i.e., at run time.
Following program demonstrates the use of pointers within a class:
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
|
#include<iostream>
using namespace std;
class Student
{
private:
string name;
string regdno;
int age;
int *marks;
public:
string branch;
void get_details();
void show_details();
void get_marks();
};
void Student::get_marks()
{
int n;
cout<<“Enter no.of subjects: “;
cin>>n;
marks = new int[n];
for(int i=0; i<n; i++)
{
cout<<“Enter subject “<<(i+1)<<” marks: “;
cin>>marks[i];
}
}
int main()
{
Student s1;
s1.get_marks();
return 0;
}
Input and output for the above program is as follows:
Enter no.of subjects: 6
Enter subject 1 marks: 20
Enter subject 2 marks: 15
Enter subject 3 marks: 16
Enter subject 4 marks: 19
Enter subject 5 marks: 20
Enter subject 6 marks: 18
|
In the above program marks is a pointer inside the class Student. It is used to allocate memory dynamically inside the get_marks() function with the help of new operator.
Local Classes
A class which is declared inside a function is called a local class. A local class is accessible only within the function it is declared. Following guidelines should be followed while using local classes:
- Local classes can access global variables only along with scope resolution operator.
- Local classes can access static variables declared inside a function.
- Local classes cannot access auto variables declared inside a function.
- Local classes cannot have static variables.
- Member functions must be defined inside the class.
- Private members of the class cannot be accessed by the enclosing function if it is not declared as a friend function.
Below example demonstrates a local class:
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
|
#include<iostream>
using namespace std;
const float PI = 3.1415;
int main()
{
class Circle
{
public:
int r;
void area()
{
cout<<“Area of circle is: “<<(::PI*r*r);
}
void set_radius(int radius)
{
r = radius;
}
};
Circle c;
c.set_radius(10);
c.area();
return 0;
}
Output of the above program is as follows:
Area of circle is: 314.15
|
0 comments:
Post a Comment