Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use anonymous classes in C++?

Tags:

I have seen anonymous classes in C++ code on Quora. It's successfully compiled and run.

Code here:

#include <iostream>  auto func() {     class // no name     {       public:              int val;     } a;      a.val = 5;      return a; }  int main() {     std::cout << func().val << std::endl;     return 0; } 

So, Is it valid in C++?

Also, I am curious to know, Is it possible to use anonymous classes in C++?

like image 476
msc Avatar asked May 25 '17 06:05

msc


People also ask

How do you use anonymous class?

Anonymous classes usually extend subclasses or implement interfaces. The above code creates an object, object1 , of an anonymous class at runtime. Note: Anonymous classes are defined inside an expression. So, the semicolon is used at the end of anonymous classes to indicate the end of the expression.

Can anonymous class be passed as a parameter?

You can supply a parameter to Anonymous Class.  parameters are passed to the superclass constructor.

Does C# have anonymous classes?

In C#, an anonymous type is a type (class) without any name that can contain public read-only properties only. It cannot contain other members, such as fields, methods, events, etc. You create an anonymous type using the new operator with an object initializer syntax.

Can Anonymous classes be implemented an interface?

No, anonymous types cannot implement an interface. We need to create your own type. Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.


2 Answers

Not only that, you can create more instances of the class by using decltype.

#include <iostream>  class  {    public:       int val; } a;   int main() {    decltype(a) b;    a.val = 10;    b.val = 20;     std::cout << a.val << std::endl;    std::cout << b.val << std::endl;    return 0; } 

Output:

10 20 
like image 80
R Sahu Avatar answered Nov 25 '22 15:11

R Sahu


In C++, an anonymous union is a union of this form:

 union { ... } ; 

It defines an unnamed object of an unnamed type. Its members are injected in the surrounding scope, so one can refer to them without using an <object>. prefix that otherwise would be necessary.

In this sense, no anonymous classes (that are not unions --- in C++ unions are classes) exist.

On the other hand, unnamed classes (including structs and unions) are nothing unusual.

union { ... } x; class { ... } y; typedef struct { ... } z; 

x and y are named object of unnamed types. z is a typedef-name that is an alias for an unnamed struct. They are not called anonymous because this term is reserved for the above form of a union.

[](){} 

Lambdas are unnamed objects of unnamed class types, but they are not called anonymous either.

like image 37
n. 1.8e9-where's-my-share m. Avatar answered Nov 25 '22 14:11

n. 1.8e9-where's-my-share m.