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

Live Demo

#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

 Live Demo

#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

Updated on: 16-Oct-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements