
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Anonymous Classes in C++
Anonymous entity is anything that is defined without a name. A class with no name provided is known as an anonymous class in c++. An anonymous class is a special class with one basic property.
As there is no name given to the class there is no constructor allocated to it, though a destructor is there for deallocating the memory block.
The class cannot be used as an element of a function i.e. you cannot pass it as an argument or cannot accept values return from the function.
The syntax for defining an anonymous class in c++
class { //data members // member fucntions }
Some programming to illustrate the working of an anonymous class in c++.
-
Creating an anonymous class and defining and using its single objects −
We will define an anonymous class and declare its objects using which we will use the members of the class.
Example
#include <iostream> using namespace std; class{ int value; public: void setData(int i){ this->value = i; } void printvalues(){ cout<<"Value : "<<this->value<<endl; } } obj1; int main(){ obj1.setData(10); obj1.printvalues(); return 0; }
Output
Value : 10
-
Creating an anonymous class and defining and using its two objects −
We can have multiple objects of an anonymous class and use them in our code. The below program show the working −
Example
#include <iostream> using namespace std; class{ int value; public: void setData(int i){ this->value = i; } void print(){ cout<<"Value : "<<this->value<<endl; } } obj1,obj2; int main(){ cout<<"Object 1 \n"; obj1.setData(10); obj1.print(); cout<<"Object 2 \n"; obj1.setData(12); obj1.print(); return 0; }
Output
Object 1 Value : 10 Object 2 Value : 12