Berkeley CSUA MOTD:Entry 28427
Berkeley CSUA MOTD
 
WIKI | FAQ | Tech FAQ
http://csua.com/feed/
2026/05/19 [General] UID:1000 Activity:popular
5/19    

2003/5/13-15 [Computer/SW/Languages/C_Cplusplus, Computer/SW/Languages/Java] UID:28427 Activity:high
5/13    Stupid C++ question but I can't get it to compile:
        struct MyStruct {};
        class Super {
        public:
          virtual void foo (MyStruct str, int* bar) = 0 {}
          virtual void foo (MyStruct str, unsigned int* bar) {
                        return foo(str, reinterpret_cast<int*>(bar)); }
        }

        class Sub : public Super {
        public:
          void foo (MyStruct str, int* bar) {}
        }

        Sub implements foo for a regular int, but should use Super's foo
        for unsigned int.  But whenever I compile I get errors about
        "invalid conversion from `unsigned int*' to `int*'" from code that
        uses an instance of Sub.  Help?
        \_ is foo virtual?
           \_ sorry, yes-- the first foo is virtual, the second is not (though
              I've tried making the 2nd virtual as well.)
        \_ I've put an explanation in ~mconst/pub/overriding-overloading;
           let me know if that answers your question.  --mconst
           \_ I had to go look it up to make sure, but your answer omits the
              using delcaration.  One solution is to add one line:
              class Sub : public Super
              {
                using Super::foo; //imports *all* overloads
                foo (MyStruct struct, int* bar);
              }
              The standard dictates that if you have the same signature from a
              using declaration and a member declaration, the member declaration
              wins. -emarkp
              \_ You're right, that is nicer; I've fixed my explanation.
                 (Unfortunately, though, it doesn't work with gcc 2.95 or
                 with Visual Studio .NET.)  --mconst
                 \_ It worked with VS .NET 2003 (7.1).  I'm not surprised if it
                    didn't work with 2002 (7.0).  The conformance is nearly
                    complete (missing exception specifications and export IIRC).
                    -emarkp
        \_ You must be explicit with each overload.  C++ rules are that if you
           hide one function, you hide *all* overloads.  Hence foo(Mystruct,
           unsigned int*) is not visible in class Sub.  See
           http://csua.org/u/ec6 -- look for "Q55" -emarkp
        \_ thanks for the helpful answers; I tried the using clause but
           didn't get instant results; this is targetted to a platform
           with a rather old version of gcc so I'm just going to suck it
           up and copy-paste into the subclasses.  Thanks again. -op
2026/05/19 [General] UID:1000 Activity:popular
5/19    

You may also be interested in these entries...
2011/3/7-4/20 [Computer/SW/Languages/C_Cplusplus] UID:54056 Activity:nil
3/7     I have a C question.  I have the following source code in two identical
        files t.c and t.cpp:
                #include <stdlib.h>
                int main(int argc, char *argv[]) {
                  const char * const * p1;
                  const char * * p2;
	...
2005/4/29-5/1 [Computer/SW/Languages/Perl] UID:37411 Activity:moderate
4/29    I need help getting information off a web site.  A page presents
        information about an item in locations spread througout the page.
        Each page presents information about one item. What is a quick and
        easy way to go through several pages, capture all the information
        related to each item, and put them into a spreadsheet with a unique
        index?  I think this might be possible by scraping the screen, but how
	...
2004/12/14-15 [Computer/SW/Compilers] UID:35291 Activity:moderate
12/14   If I have a C function like this
        void foo(void) {
          static const char unused1[] = "one";
          const char * const unused2 = "two";
          ...... some code ......
          return;
	...
2004/11/5-7 [Computer/SW/Languages/C_Cplusplus] UID:34697 Activity:high
11/5    In C, why is the "offsetof" macro defined to be of type size_t but not
        ptrdiff_t?  Thx.
        \_ Probably because ptrdiff_t is signed and size_t isn't.
           \_ How does being signed make ptrdiff_t less portable?
              \_ Imagine a 16-bit C implementation, where int is 16 bits, long
                 is 32 bits, and the maximum object size is 64k - 1.  size_t
	...
2004/8/30-31 [Computer/SW/Languages/C_Cplusplus] UID:33228 Activity:high
8/30    Ok this is pretty basic but... is there a way to "escape" text to
        avoid it being substituted by C preprocessor macro expansion?
        \_ Wouldn't that functionality make C preprocessing as powerful as
           lisp's quasiquote/escape? -- ilyas
           \_ Squish!  Isn't it illegal to talk about lisp on the motd?!
        \_ In general no.
	...
2004/8/18-19 [Computer/SW/Languages/C_Cplusplus] UID:32995 Activity:very high
8/18    Doesn't math.h define min() and max() functions?  What should I include
        to get them?  I'd rather not do the (a < b) ? a : b thing.  Thx
        \_ No.  Many programmers define it as a new macro.  Don't know what
           gcc people do, offhand.
        \_ OS X has fmin(3)/fmax(3) which conform to ISO/IEC 9899:1999(E).
           Linux might have these too.
	...
2004/8/10-11 [Computer/SW/Languages/C_Cplusplus, Computer/SW/Compilers] UID:32805 Activity:high
8/10    C question.  Is there anything wrong with the following?
        const my_struct_t **pp;
        pp = malloc(sizeof(my_struct_t *));
        pp = realloc(pp, sizeof (my_struct_t *) * 2);
        "gcc -Wall" doesn't complain.  But the M$ compiler (cl.exe) complains
        about the realloc line:
	...
2004/7/13-14 [Computer/SW/Languages/C_Cplusplus] UID:32265 Activity:high
7/12    Someone please explain the following?
        ((size_t )& ((SomeVar *)0)->Field);
        \_ It's a hideous abuse of C++ syntax and results in undefined
           behavior.  It appears to be an attempt to find out the offset of the
           member "Field" in the class/struct type SomeVar.  Ow, ow ow.
           \_ This is actually not undefined, in C or C++.  It is hideous,
	...
2004/7/5 [Computer/SW/Languages/Perl] UID:31164 Activity:high
7/4     Is there something like a macro in Perl?  Couldn't find any in
        the Camel book.
        \_ If you truly need macros in Perl, you probably want AUTOLOAD.
           Of course, if you truly need macros, Perl is the wrong language for
           what you are doing.  -- ilyas
        \_ I don't know perl, but don't almost all interpreted languages have
	...
2004/5/28-29 [Computer/SW/Compilers] UID:30481 Activity:nil
5/28    I just found out that bison inserts these lines of code
                #ifndef __cplusplus
                #ifndef __STDC__
                #define const
                #endif
                #endif
	...
2003/8/29-2004/2/14 [Computer/SW/Languages/C_Cplusplus] UID:12260 Activity:nil
2/13    Where can I get c macro specifications? What keywords to look in
        google?
        \_ You might also want to find a good book on the specification of
           English, so you don't have to look like an ignorant tool asking
           a simple C question.
        \_ what do you want to know?  There's the C language spec that you
	...
2013/5/1-18 [Computer/SW/Languages/Java, Computer/Theory] UID:54669 Activity:nil
5/1     What's the difference between CS and Computer Engineering?
        http://holykaw.alltop.com/top-ten-paying-degrees-for-college-graduates
        \_ One is science and the other is engineering.
        \_ From http://en.wikiquote.org/wiki/Computer_science
           'A folkloric quotation ... states that "computer science is no more
           about computers than astronomy is about telescopes."  The design
	...
2012/12/4-18 [Computer/SW/Languages/Java] UID:54544 Activity:nil
12/4    Holy cow, everyone around me in Silicon Valley is way beyond
        middle class according to Chinni's definition:
        http://en.wikipedia.org/wiki/American_middle_class
        \_ Let's set our goals higher:
           http://en.wikipedia.org/wiki/Upper_middle_class_in_the_United_States
           \_ How about this one?
	...
2012/10/29-12/4 [Science/Disaster, Computer/SW/Languages/Java, Politics/Domestic/President/Bush] UID:54516 Activity:nil
10/29   Go Away Sandy.
        \_ Sorry, Coursera is performing preventive maintenance for this
           class site ahead of Hurricane Sandy. Please check back in 15 minutes.
           class site ahead of Hurricane Sandy. Please check back in 15
           minutes.
        \_ Bitch.
	...
2012/1/18-3/3 [Computer/SW/Languages/Java, Finance/Investment] UID:54290 Activity:nil
1/18    I own a bunch of NFLX stocks bought at several different periods
        (from high $200 all the way down to $80). I dumped a few and
        still have a few. Why the hell is Reid Hastings still making
        $500,000/year? How do I join the pending NFLX Class Action
        Lawsuit?
        \_ Why would you buy stock in a company run by a narcissistic
	...
Cache (8192 bytes)
csua.org/u/ec6 -> groups.google.com/groups?selm=CLINE.94Jul12094407%40cheetah.clarkson.edu&oe=utf-8&output=gplain
A: Life as we know it suddenly comes to a catastrophic end. It is the programmer's --not the compiler's-- responsibility to get the connection between new and delete correct. If you get it wrong, neither a compile-time nor a run-time error message will be generated by the compiler. A: Constructors (ctors) do not return any values, so no returned error code is possible. The best way to handle failure is therefore to throw' an exception. If your compiler doesn't yet support exceptions, several possibilities remain. The simplest is to put the object itself into a half baked' state by setting an internal status bit. Naturally there should be a query (inspector') method to check this bit, allowing clients to discover whether they have a live object. Other member functions should check this bit, and either do a no-op (or perhaps something more obnoxious such as abort()') if the object isn't really alive. Check out how the iostreams package handles attempts to open nonexistent/illegal files for an example of prior art. A: This will NOT work, since comments are parsed before the macro is expanded: #ifdef DEBUG_ON #define DBG #else #define DBG // #endif DBG cout << foo; A: A program is const correct' if it never mutates a constant object. A: Declaring the constness' of a parameter is just another form of type safety. It is almost as if a constant String, for example, lost' its various mutative operations. If you find type safety helps you get systems correct (especially large systems), you'll find const correctness helps also. A: Type safety requires you to annotate your code with type information. In theory, expressing this type information isn't necessary -- witness untyped languages as an example of this. However in practice, programmers often know in their heads a lot of interesting information about their code, so type safety (and, by extension, const correctness) merely provide structured ways to get this information into their keyboards. Every const' you add over here' requires you to add four more over there'. The snowball effect is magnificent -- unless you have to pay for it. Long about the middle of the process, someone stumbles on a function that needs to be const but can't be const, and then they know why their system wasn't functioning correctly all along. This is the benefit of const correctness, but it should be installed from the beginning. A: A const member function is a promise to the caller not to change the object. Put the word const' after the member function's signature; C++ compilers aren't allowed to assume the bitwise const, since a non-const alias could exist which could modify the state of the object (gluing a const' ptr to an object doesn't promise the object won't change; I talked to Jonathan Shopiro at the C++AtWork conference, and he confirmed that the above view has been ratified by the ANSI-C++ standards board. This doesn't make it a perfect' view, but it will make it the standard' view. These different categories of member fns are distinguished by whether the member fn is const' or not. A: In current C++, const member fns are allowed to cast away the const-ness of the "this" ptr'. Programmers use (some say misuse') this to tickle internally used counters, cache values, or some other non-client-visible change. Since C++ allows you to use const member fns to indicate the abstract/meaning-wise state of the object doesn't change (as opposed to the concrete/bit-wise state), the meaning' of the object shouldn't change during a const member fn. Those who believe const' member fns shouldn't be allowed to change the bits of the struct itself call the abstract const' view Humpty Dumpty const' (Humpty Dumpty said that words mean what he wants them to mean). The response is that a class' public interface *should* mean exactly what the class designer wants it to mean, in Humpty Dumpty's words, nothing more and nothing less'. If the class designer says that accessing the length of a List doesn't change the List, then one can access the length of a const' List (even though the len()' member fn may internally cache the length for future accesses). Some proposals are before the ANSI/ISO C++ standards bodies to provide syntax that allows individual data members to be designated as can be modified in a const member fn' using a prefix such as const'. This would blend the best of the give the compiler a chance to cache data across a const member fn', but only if aliasing can be solved (see next question). A: If the object is constructed in the scope of the const member fn invocation, and if all the non-const member function invocations between the object's construction and the const member fn invocation are statically bound, and if every one of these invocations is also inline'd, and if the ctor itself is inline', and if any member fns the ctor calls are inline, then the answer is Yes, the soon-to-be-standard interpretation of the language would prohibit a very smart compiler from detecting the above scenario, and the register cache would be unnecessarily flushed'. The reader should judge whether the above scenario is common enough to warrant a language change which would break existing code. A: Inheritance is what separates abstract data type (ADT) programming from OOP. In fact, everything discussed so far could be simulated in your garden variety ADT programming language (ex: Ada, Modula-2, C with a little work , etc). Inheritance and the consequent (subclass) polymorphism are the two big additions which separate a language like Ada from an object-oriented programming language. A: Human beings abstract things on two dimensions: part-of and kind-of. We say that a Ford Taurus is-a-kind-of-a Car, and that a Ford Taurus has parts such as Engine, Tire, etc. The part-of hierarchy has been a first class part of software since the ADT style became relevant, but programmers have had to whip up their own customized techniques for simulating kind-of (usually in an ad hoc manner). An example of kind-of decomposition', consider the genus/species biology charts. Knowing the internal parts of various fauna and flora is important for certain applications, but knowing the groupings (kinds, categories) is equally important. A: In addition to being an abstraction mechanism that makes is-a-kind-of relationships explicit, inheritance can also be used as a means of incremental programming'. A derived class inherits all the representation (bits) of its base class, plus all the base class' mechanism (code). Another device (virtual functions, described below) allows derived classes to selectively override some or all of the base class' mechanism (replace and/or enhance the various algorithms). This simple ability is surprisingly powerful: it effectively adds a third dimension' to programming. After becoming fluent in C++, most programmers find languages like C and Ada to be flat' (a cute little book, Flatland', aptly describes those living in a two dimensional plane, and their disbelief about a strange third dimension that is somehow neither North, South, East nor West, but is Up'). As a trivial example, suppose you have a Linked List that is too slow, and you wish to cache its length. You could open up' the List class' (or module'), and modify it directly (which would certainly be appropriate for such a simple situation), but suppose the List's physical size is critical, and some important client cannot afford to add the extra machine word to every List. Another option would be to textually copy the List module and modify the copy, but this increases the amount of code that must be maintained, and also presumes you have access to the internal source code of the List module. The OO solution is to realize that a List that caches its length is-a-kind-of-a List, so we inherit: class FastList : public List { public: //override operations so the cache stays hot' protected: int length; A: The short answer: yes -- you don't even need the cast'. Long answer: a derived class is a specialized version of the base class (Derived is-a-kind-of-a Base'). The upward conversion is perfectly safe, and happens all the time (a ptr to a Derived is in fact pointing to a sp...