home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!gumby!yale!yale.edu!think.com!barmar
- From: barmar@think.com (Barry Margolin)
- Newsgroups: comp.lang.c++
- Subject: Re: name of object
- Date: 28 Jan 1993 20:58:22 GMT
- Organization: Thinking Machines Corporation, Cambridge MA, USA
- Lines: 80
- Message-ID: <1k9hdeINNjdq@early-bird.think.com>
- References: <g++FAQ_01_15_1993_texi@ohm.berkeley.edu> <g++FAQ_01_15_1993_plain@ohm.berkeley.edu> <1993Jan28.173602.5232@gmuvax2.gmu.edu>
- NNTP-Posting-Host: telecaster.think.com
-
- In article <1993Jan28.173602.5232@gmuvax2.gmu.edu> twallace@gmuvax2.gmu.edu (Todd Wallace) writes:
- >Here is an odd question for the OOP gurus:
- >Is there a way for an object to know its own name?
-
- There's no built-in way in the language. Some objects don't even have
- names.
-
- >For instance, let's say we declare the following class:
- >class Lemon {
- > public:
- > //some stuff
- >};
- >
- >void main(void)
- >{
- > Lemon A,B,C;
- >
- > A.tell_me_your_name;
- > B.tell_me_your_name;
- > C.tell_me_your_name;
- >}
-
- How's this:
-
- class NamedThing {
- char *name;
- public:
- void tell_me_your_name() {cout << name << '\n';};
- NamedThing(char *initial_name) {name = initial_name;};
- };
-
- class Lemon: virtual public NamedThing {
- ...
- };
-
- void main(void) {
- Lemon A("A"), B("B"), C("C");
- A.tell_me_your_name;
- B.tell_me_your_name;
- C.tell_me_your_name;
- }
-
- If you don't like having to write the name twice, use a macro:
-
- #define NAMED(name) name(#name)
-
- Then you can write:
-
- Lemon NAMED(A), NAMED(B), NAMED(C);
-
- Lemon *foo_ptr = NAMED(foo);
-
-
-
- >
- >and I would like the output to be:
- >A
- >B
- >C
- >
- >Therefore, I have to declare a member function for Lemon that
- >can look up its own name.
- >
- >Can it be done? It would help a lot with debugging.
- >
- >
- >----------------------------------------------------------------
- >| Todd Wallace | "A pessimist is surprised |
- >| twallace@gmuvax2.gmu.edu | as often as an optimist, |
- >| | but always pleasantly." |
- >| | - Robert Heinlein |
- >----------------------------------------------------------------
- >
-
-
- --
- Barry Margolin
- System Manager, Thinking Machines Corp.
-
- barmar@think.com {uunet,harvard}!think!barmar
-