When there is a need to create a read-only object, the object can be declared as a constant object using the const keyword. Syntax for creating a constant object is as follows:
ClassName const object_name(params-list);
Following are the characteristics of a constant object:
- Constant object can be initialized only through a constructor.
- Data members of a constant object cannot be modified by any member function.
- Constant object are read-only objects.
- Constant objects should be accessed only through constant member functions.
Following program demonstrates a constant object:
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
|
#include <iostream>
using namespace std;
class Student
{
private:
string name;
string regdno;
int age;
string branch;
public:
Student(string br)
{
branch = br;
}
void get_branch() const
{
cout<<“Branch is: “<<branch;
}
};
int main()
{
Student const s(“CSE”);
s.get_branch();
return 0;
}
Output for the above program is as follows:
Branch is: CSE
|
Anonymous Objects
An object which has no name is known as an anonymous object. Syntax for creating an anonymous object is as follows:
ClassName(params-list);
An anonymous object can be created and used in any statement without using any name. It is automatically destroyed after the control moves on to the next statement. Following program demonstrates an anonymous object:
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
|
#include <iostream>
using namespace std;
class Student
{
private:
string name;
string regdno;
int age;
string branch;
public:
Student(string reg)
{
regdno = reg;
cout<<“Student with regdno “<<regdno<<” is created”;
}
};
int main()
{
Student(“501”); //Anonymous object
return 0;
}
Output for the above program is as follows:
Student with regdno 501 is created
|
Following are the advantages of anonymous objects:
- They result in cleaner, shorter, and efficient code.
- There is no need to name objects which are going to be used temporarily.
- No need to declare them.
- Unnamed are objects are destroyed automatically after their use is over.
Take your time to comment on this article.
EmoticonEmoticon