• Advertisement

Archived

This topic is now archived and is closed to further replies.

Advanced: Anonymous classes (C++)?

This topic is 5678 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can anyone shed light on the uses of anonymous classes in C++? I''ve discovered that compilers will internally identify/name-mangle the class(es) (generally, variations on CRC file #s and Perl-like $_ constants), so the functionality is obviously supported. When would it be useful and what common (ha!) or popular applications exist? [Note: If you don''t know, don''t speculate. Just zip it and keep moving. Thank you.]

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
You can do this in Java, but C++ doesn''t support anonymous classes. In Java anonymous classes are useful for giving class definitions that respond to events in place, rather than having the definition elsewhere. It''s also useful for providing predicates in the form of functors (functions wrapped in a struct/class) in place as opposed to putting the definition elsewhere. I like this because when the code is elsewhere it disassociates the functionality from where it is actually used. Anonymous classes solve this problem.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
You can use anonymous structs(I presume classes can be used in the same way)as members of a union.

For example:
typedef union {
struct {int X; int Y};
struct {char A; char B};
int Z;
} XandYorAandBorZ;

Thus, x and y would be the members of the union, or a and b would be the (entire) contents of the union, or z by itself could be the contents of the union.

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
You can use anonymous structs(I presume classes can be used in the same way)as members of a union.



This is not standard. Anonymous nested union, yes. Anonymous nested struct, no.

Oluseyi:

I assume you mean class { /*...*/ } foo;, just like you may do struct { /*...*/ } bar;. Since the only difference between class and struct are the default access permissions, I can only imagine it would be used in the same cases : as a singleton of sorts (without a class name, you can't have a custom constructor or destructor, nor create new instances), whether at global scope, or nested within another class.

I have seen unnamed structs used mainly as global tables of some kind : struct { /*...*/ } const foo[] = { /* ... */ };. Using class instead of struct makes little difference, especially when you consider that class : public foo { /*...*/ } bar; gives parse errors.

I hope I wasn't too speculative for you

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]


[edited by - Fruny on June 30, 2002 7:14:37 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
You can do this in Java, but C++ doesn''t support anonymous classes. In Java anonymous classes are useful for giving class definitions that respond to events in place, rather than having the definition elsewhere.

Interesting. As Fruny pointed out, though, C++ supports anonymous classes/structs for instantiation of a single object or set of objects declared and defined along with the class (class {/*...*/} x; variety). Could you give an example of an anonymous class in Java that responds to events in-place?

quote:

It''s also useful for providing predicates in the form of functors (functions wrapped in a struct/class) in place as opposed to putting the definition elsewhere. I like this because when the code is elsewhere it disassociates the functionality from where it is actually used. Anonymous classes solve this problem.

C++ supports nested classes as well as local classes, which can be very useful since it doesn''t permit local functions. If you wish to provide, say, a predicate function that is only ever used within the current scope, wrap said function as a functor:

int SomeFunction( int x )
{
struct Pred
{
bool operator () ( int & i)
{/* yadda */}
} pred;
 
some_stl_algorithm( some_container.begin(), some_container.end(),
pred );
}

Obviously, combining this example with earlier comments on immediate instantiation, it should be possible to omit the class identifier Pred in the code above.

Thanks AP and Fruny. And no, you weren''t speculative by a long shot; you merely both reminded me of language features moved to the back of my mind.

Share this post


Link to post
Share on other sites
I tried without the name in VC7, I got a 'C2627' - member function defined in unnamed class. Interestingly, the symbol name for the named class was ::main::Foo.

I vaguely remember some design difference between C and Pascal where Pascal can have local functions, but C can have static variables... (some dynamic scoping and lifetime issues IIRC)

If somebody could enlighten me...

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]


[edited by - Fruny on June 30, 2002 11:48:00 PM]

Share this post


Link to post
Share on other sites
anonymous classes are used extensively in java in UI programming. for example, the following code adds program termination capability to a Button reference.


      
// anonymous class in the function call.

quitButton.addActionListener( new ActionListener( ){

// in place event response

public void actionPerformed( ActionEvent e ){
terminate( );

}
});


honestly, I am not well versed enough in C++ to respond about such things in it.


[edited by - lucinpub on July 1, 2002 2:40:14 AM]

Share this post


Link to post
Share on other sites
Every GUI component in Java should ideally have its own *Listener. Imagine if you had 20 buttons on screen, w/o anonymous innerclasses, you'd have to create 20 different classes that implemented an ActionListener interface.

Anonymous inner classes can be used to simulate multiple inheritance in Java. For a better example, check out the chapter on inner classes in the book Thinking in Java.

EDIT: p.s.: In Java, every use of an anonymous inner class can be done w/o using anonymous inner classes. I think it boils down to a matter of style.



[edited by - NuffSaid on July 1, 2002 8:03:45 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by Oluseyi
C++ supports nested classes as well as local classes, which can be very useful since it doesn''t permit local functions. If you wish to provide, say, a predicate function that is only ever used within the current scope, wrap said function as a functor

Not on MSVC. Don''t know if this is a compiler shortcoming, but it won''t allow you to instantiate a template from a function-local class definition, which means no functors for STL algorithms. If anybody knows a way around this, I''ll name my first-born after you.

Share this post


Link to post
Share on other sites
From the article Fruny linked:


A local or unnamed class cannot be
used as a template parameter. From the C++ standard
(14.3.1/2):

A local type, a type with no linkage, an unnamed
type or a type compounded from any of these types
shall not be used as a template-argument for a
template type-parameter. [Example:

template <class T>
class X { /* ... */ };

void f()
{
struct S { /* ... */ };
X<S> x3; // error: local type used as
// template-argument
X<S*> x4; // error: pointer to local type
// used as template-argument
}

--end example]

Share this post


Link to post
Share on other sites
quote:
Original post by Stoffel
it won't allow you to instantiate a template from a function-local class definition, which means no functors for STL algorithms. If anybody knows a way around this, I'll name my first-born after you.

I don't know if that's what you're looking for, but you can declare local functions this way:

void SomeFunction(){
vector< int > v;
class Pred {public:
static bool comp( int & i, int &j){return true;}
};
sort( v.begin(), v.end(), Pred::comp);
}

It's not quite a functor, but I can't think of a disadvantage to this technique in this context.

Cédric

[edited by - cedricl on July 1, 2002 8:20:56 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by NuffSaid
Every GUI component in Java should ideally have its own *Listener. Imagine if you had 20 buttons on screen, w/o anonymous innerclasses, you''d have to create 20 different classes that implemented an ActionListener interface.

[edited by - NuffSaid on July 1, 2002 8:03:45 AM]


I''d disagree that every component should have its own listener... When you have 20 or 30 components, the time it takes to load all of those classes can add up. I think using the Dynamic Proxy API''s is a better solution when you have more than 20 or so Listeners of the same type. It cuts down on the number of classes that need to be loaded significantly.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Oluseyi
[Note: If you don''t know, <strong>don''t speculate</strong>. Just zip it and keep moving. Thank you.]


Your a bit of an elitist aren''t you? Maybe it''s time for you to move onto comp.lang.c++; your arrogance appears to have reached the right level.

To be on topic though, the only use I''ve ever seen is for singletons, which includes making a clever ''null'' object that can be implicitally casted to any pointer type.

Share this post


Link to post
Share on other sites
quote:
Original post by cedricl
I don''t know if that''s what you''re looking for, but you can declare local functions this way:


Man, my first-born is gonna get beat-up a lot with a name like cedricl. Thanks, looks like the key was making the function static--never even thought of that.

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
Your a bit of an elitist aren''t you?

No, I just think that random speculation will only serve to muddy the waters and further confuse the issue. You never thought of that, did you?

All you folks always decrying others as "elitists"... I have a profile; take a look at my recent posts and threads and then make an assessment. Don''t try to divine who I am off of one post. Scheissekopf.

quote:

To be on topic though, the only use I''ve ever seen is for singletons, which includes making a clever ''null'' object that can be implicitally casted to any pointer type.

Do you have an example of this. It sounds interesting.

Share this post


Link to post
Share on other sites
I was gonna make a reply but you said no random speculation.

A possible reason for putting in a annoymous class is packing and memory alignment. Perhaps you want to glocals (a global that is local to a cpp file) be aligned (God knows why).

Another possible is for the nifty counter singleton technique. There we need a local counter for each cpp file (glocal), and putting it in the private section of an annoymous class mays it inaccessible to people. Nice idea, I might go try.

Share this post


Link to post
Share on other sites
quote:
Original post by Void
Another possible is for the nifty counter singleton technique. There we need a local counter for each cpp file (glocal), and putting it in the private section of an annoymous class mays it inaccessible to people. Nice idea, I might go try.


That''s what the anonymous namespace is for.


Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Oluseyi
No, I just think that random speculation will only serve to muddy the waters and further confuse the issue. You never thought of that, did you?

All you folks always decrying others as "elitists"... I have a profile; take a look at my recent posts and threads and <em>then</em> make an assessment. Don''t try to divine who I am off of one post. Scheissekopf.



I just don''t think it''s very nice for you to try to stop people who don''t think they are that advanced from getting involved because they feel they are not on the same level as you. It doesn''t take long to skip over speculative posts and it just looks a bit arrogant that you have to tell people what they can and can''t say. Plus, you''ll get them anyway.

quote:

Do you have an example of this. It sounds interesting.


From Effective C++:


const // this is a const object...
class {
public:
template<class T> // convertible to any type
operator T*() const // of null non-member
{ return 0; } // pointer...

template<class C, class T> // or any type of null
operator T C::*() const // member pointer...
{ return 0; }

private:
void operator&() const; // whose address can''t be
// taken (see Item 27)...

} NULL; // and whose name is NULL

Share this post


Link to post
Share on other sites
quote:
Original post by Fruny
That''s what the anonymous namespace is for.



It''s different.


  
namespace
{
Foo f;
}

class
{
private:
Foo f1;
} Unnamed_class_instance;


Using annoymous namespace, we (the client) can still access f.

But we cannot access f1 if it is inside the private section although the client can access Unnamed_class_instance.

Share this post


Link to post
Share on other sites

  • Advertisement