Anonymous classes in C++

Anonymous Classes in C++

Anonymous class is a class with no name. The main advantage of using an anonymous class is that it provides reusability of the class. Also anonymous class helps in encapsulation of data. Anonymous class is basically used when only one instance of the class is needed and it has only a short body. By defining an anonymous class, it does the same steps of defining a local class and instantiating it. The anonymous class is rightly used after it is defined. Following specifies an example of anonymous class in C++.

class
{
int a;
} c1;

Here, c1 is an object of the anonymous class. Usually, anonymous classes in C++ are defined using "typedef" ( a keyword to assign alternative names to existing types). Typedef helps in giving another name to the class. It is shown as below:

typedef class
{
int a;
} newclass;
newclass c2;

Here newclass is the object of the anonymous class and c2 is its instance.

Member variables can also be initialized in anonymous class in C++. It is done as follows: -

typedef class
{
int a;
} newclass = {6};


Here, when we instantiate the class, a new instance of the class will be created with member function 'a' initialized as 6.

Anonymous class in java is also the same. In java an anonymous class may implement an interface or extend a super class, but may not be declared to do both.

Thank you for reading the post. Comments / suggestions are always welcome.


Comments

  1. Firstly thank you so much for your guidance .Please can you explain what will be the scope of object created using this anonymous class and how can we achieve encapsulation using anonymous class?

    ReplyDelete

Post a Comment

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix