Advertisement

Classes Vs. Straight Code

Started by June 26, 2000 01:30 PM
91 comments, last by farmersckn 24 years, 5 months ago
And I thought I had a lot of time on my hands...
Anyway, remember when you said this, null-pointer?
quote: (In regards to C++ in relation to C)
No, it's not slower. Of course, it depends on what code you are comparing. Poorly written C code may be faster than properly written C++ code, but properly written C code shouldn't be any faster than properly written C++ code.

Ever heard of the this pointer? It's passed to every member function you call. But it hardly slows anything down. That's what I meant. So next time don't say we don't know what we're talking about if you don't.

lntakitopi@aol.com - http://www.geocities.com/guanajam

Edited by - SHilbert on July 4, 2000 5:27:14 PM
Watch out! This is gonna be the longest reply in history!!

...just kidding


EvilTwin: He is definitely talking about types in C++, because that''s the argument he launches into from the get-go.

SHilbert: Obviously, I know what the "this" pointer is. I was referring to this misconception:


MISCONCEPTION: Code snippet A is faster than code snippet B.

Code snippet A:


void Function(Class* Object, int x)
{
// ...
}



Code snippet B


void Class::Function(int x)
{
// ...
}



In fact, if B''s implicit "this" pointer is stored in ECX, and several functions are called on the object in a row (versus several functions in C), then its possible that B would be slightly faster than A. Of course, I doubt this is true in real life with good C optimization. The fact of the matter is that C with typical structural programming (using structures to hold instance data) isn''t any faster than C++ classes.

C programmers just have a tendency to think that everything the compiler generates for them is slow. That''s probably just a left-over from the bygone days of total hand optimization and massive quantities of assembly code. ahh...the good old days...





- null_pointer
Sabre Multimedia
Advertisement
quote:
EvilTwin: He is definitely talking about types in C++, because that''s the argument he launches into from the get-go.


Maybe you''re right, but after looking at it again, I definitely get the impression that his "Too Much Typing" section was about
typing on the keyboard. First of all, he says:
quote:
"Typing is such a tiny fraction of programming that it''s not a big deal."

He''d have to be a complete idiot to say that about data types, and although he makes some poor arguments against C++, it doesn''t seem like that''s the case.

quote:
Having to add that prototype is annoying ''accidental'' effort; there is no reason this redundancy must be shoveled onto the programmer (it could easily be automatically generated, a la Java or Borland''s Turbo Pascal).

Here he says that adding a prototype is an "accidental" effort, suggesting that his earlier comment about typing being "accidental" work was about the act of typing code into an editor rather than data typing.

He goes on to describe the exact procedure for copying and pasting a function declaration from its definition:
quote:
Whether this worked out by chance or not, these are easy editting operations to perform without moving your hands from the keyboard; cut a single line (in ''vi'', ''yy''; in a windows editor: home, shift-end, ctrl-c), switch buffers, paste, go to beginning of line and type ''extern'', go to end of line and type '';''.

Then he complains about the added burden of removing the class name for the declaration of a member function:
quote:
To make the C++ cut and paste, I don''t need to add ''extern'' at the front. Instead I have to reach into the middle of the declaration and delete the ''Foo::''. This is actually more work--at least for me, it takes longer, and more thinking, to do this. (You have to actually parse the declaration, which gets more complex as the return value type gets more complex.)

None of this contains any criticism of data types in C++, so it seems to me that in this section, he''s just complaining about how the syntax of member function declarations forces him to hit more keys than he needed to when declaring C functions.
oh my, null_pointer of all the C++ zealots i''ve met... you''re not the most convincing, but you''re definatly the most arrogant. and, stating personal opinions is something i don''t find very amusing, but i hope the readers have enough understanding of C and C++ to see the difference between your "FACT"s and your opinions...
anyway, since noone wrote that C++ program in C, i felt like i had to, just to annoy you...
--
#include

typedef struct point {
int x, y;
} point;

void scale(point *p, const int factor)
{ /* i thought scaling a meant multiplying by a factor... oh well */
p->x += factor;
p->y += factor;
}

void main() /* actually, main is supposed to return an int... */
{
char *hello = "Hello", *world = "World!";
char hello_world[256];
point p1 = { 100, 100 }, p2 = { 210, 500 };
FILE *file;

scale(&p1, 5);
scale(&p2, 100);
strcpy(hello_world, hello);
strcat(hello_world, " ");
strcat(hello_world, world);

printf("%i %i\n", p1.x, p1.y);
printf("%i %i\n", p2.x, p2.y);
printf("%s\n", hello_world);

file = fopen("output.txt", "w");
fprintf(file, "%i %i %i %i %s", p1.x, p1.y, p2.x, p2.y, hello_world);
}
--
i''m not as arrogant like you, so i won''t claim that C is better than C++ just because this example is shorter than the C++ version, because that simply would not be true. and this is a bad example program, btw... i understand that you wanted to show off fstream and operator overloading, but... (this program can probably be made cleaner and more optimized, since i haven''t slept for 45 hours)

oh, and don''t come and say that i''m trying to "simulate" C++, i might as well say that YOU are trying to "simulate" Java your C++ code.

say what you want about C, but at least most compilers support the ANSI C standard. yeah yeah, i know there''s a standard for ANSI C++, too (finally), but Visual C doesn''t seem to support it (can''t remember who said something about ANSI C++ templates and VC).

and by the way, if you want a really good OOP language, try Java. it''s a much much better language than C++ ...

// Siigron
heh heh yet another coder who says my facts are wrong but won''t (or can''t) dispute them...

TIP: If you want to debate something, why not debate something I have addressed to specifically to you, or to everyone? Why must people keep taking my replies out of context, and making like I''m some kind of an idiot?

TIP: When people are angry, they usually provide an amazingly accurate self-analysis.


And now that you''ve done the sample program, let''s move on to something more practical: containers. Add code to use a linked list like this in C:

(Note: These exercises are going to become increasingly difficult in C.)


// additional include:
#include

// appendix to main():
list&ltpoint> points;

points.push_back(p1);
points.push_back(p2);
points.push_back(point(50, 200));
points.push_back(point(750, 234));

points.pop_back();

points.push_back(320, 349);



How much code does it take to do that linked list traversal in C? What that code does is create a list of points, add the two points to the end of the list, construct two more points and add them to the end of the list, remove the last point from the list, and add another point to the list. Of course, if you really want to emulate what templates do, you need to write code that will call the destructors of the types, cleaning up dynamic memory etc. Oops! C doesn''t support destructors...well, just make a method to clean all of that up, and the user will call it. And one more thing - your list has to work with any object, so you can''t modify your point struct (or future classes) to work with your list.

Once you get that sample re-written, we''ll add in another list object (using a different object type) and possibly a map object.


Finally, the fact that writing structural code in C is emulating C++ is true. Here''s how it works. You''ve got a brain. That brain works in a particular way, very similar in concept to computers, according to the complex set of rules, which we call science. C++ models how that brain works much more accurately than C. C programmers who adopt methods according to what they see happening in C++ circles are emulating C++. Thus when I say that a particular piece of C code emulates a feature of C++, that particular C code is doing a poor job (either in speed, code size, bad typing, memory usage, etc. or any combination of the those) of doing what the C++ feature does.


Really, I don''t care about sounding like a know-it-all. I only want to correct some very common misconceptions about C++. You forget, you are not the authority on all things coding, and it''s entirely possible there are flaws in your logic. (It''s possible there are flaws in my logic, but no one will demonstrate that, so we won''t ever know.)




- null_pointer
Sabre Multimedia
quote: Original post by Anonymous Poster

Visual C doesn''t seem to support it (can''t remember who said something about ANSI C++ templates and VC).

and by the way, if you want a really good OOP language, try Java. it''s a much much better language than C++ ...



I was probably the one who mentioned Visual C++ ''s crappy support of templates. It annoys me to no end, because it''s the greatest tool of all for a performance library programmer.
*sigh* But it''s actually not an argument against C++, it''s an argument against the blind adherence to the C standard in the visual studio compiler. "Oh, if we just put little bits in, they''ll never notice."

Java a better OOP language than C++? Hmm, let me think about this thoroughly. I think I agree with you, however, as you have noticed, I''m a bigger fan of generic programming than of OOP.
Java''s problem is compilers. As a language it''s fine, just like C++ is fine as a language. But C++''s compilers are more mature than the Java ones ( and don''t even get me started on the VM architecture and HUGE errors with thread scheduling, ugh ), which gives C++ the implementation edge.



About Null''s mammoth post - I''m impressed that you spent so much time debunking the article logically.
However, just to be annoying, I''m going to "get you" on one little thing:
quote: ( About "static functions" )
Declare them private in the header file. Sorry, but to add an implicit this pointer, C++ must have the function declared in the class declaration. There can be only one class declaration, or else everybody and his uncle could add things to your classes.

For a class-static file, you do not need an implicit this pointer. In fact, there is no implicit this pointer passed, because you do not need an object to call a class-static function.
However, the rest of the argument is still valid, you need the declaration in the SINGLE class declaration, because otherwise it would never become "final" ( is that a Java keyword? AP was right, Java is a better OOP language ).

It all comes down to the fact that, without "interfaces" ( simulation through abstract base classes/multiple inheritance ), you need the FULL declaration of the class to make it final, without the ability to hide it very well, or you have to use the interfaces hack which you MIGHT argue is a little bit weak.

Give me one more medicated peaceful moment.
~ (V)^|) |<é!t|-| ~
ERROR: Your beta-version of Life1.0 has expired. Please upgrade to the full version. All important social functions will be disabled from now on.
It's only funny 'till someone gets hurt.And then it's just hilarious.Unless it's you.
Advertisement
Ok, I use both C and C++ and I have to wade in here and fix some of the ''FACT''s that are incorrect in the 10 minutes I will give.

FACT: C is a subset of C++.
Incorrect. C is neither a syntactic nor symantic subset of C++.
Syntactic: f() in C means a function that takes any number of arguments but in C++ it means a function that takes no arguments.
Symantic: sizeof(''x'') in C means sizeof(int) but in C++ means sizeof(char).
So the code:
if (sizeof(''x'') == 1) {...}
has different results in C and C++.

FACT: Working with other people’s code is easier under C++.
Incorrect. As an article in IEEE computer shows C++ code may take many times the amount of maintenance of an equivalent C program even with expert C++ coders.

FACT: Types require overloaded operators.
Incorrect. That is only syntactic sugar. The symbol ''+'' is used by int, float, double etc. and is overloaded but there is no theoretical reason for the overloading.

FACT: Properties like commutative and associative are only properties of certain types of numbers, not different types of operators.
Incorrect. Actually it is the combination of "numbers" and "operators" that define things such as groups, fields and types.

FACT: An Object-Oriented Programming language needs to support data encapsulation.
Incorrect. There is no need theoretically. In C++ just make everything public. No encapsulation but it is object oriented.

FACT: Strong typing prevents stupid mistakes and makes poor coding skills evident.
Incorrect. See almost any C++ code written by someone who is learning algorithms.






Let''s see...
"Finally, the fact that writing structural code in C is emulating C++ is true. Here''s how it works. You''ve got a brain. That brain works in a particular way, very similar in concept to computers, according to the complex set of rules, which we call science. C++ models how that brain works much more accurately than C. C programmers who adopt methods according to what they see happening in C++ circles are emulating C++. Thus when I say that a particular piece of C code emulates a feature of C++, that particular C code is doing a poor job (either in speed, code size, bad typing, memory usage, etc. or any combination of the those) of doing what the C++ feature does."

Becomes...

Finally, the fact that writing object oriented code in C++ is emulating Java is true. Here''s how it works. You''ve got a brain. That brain works in a particular way, very similar in concept to computers, according to the complex set of rules, which we call science. Java models how that brain works much more accurately than C++. C++ programmers who adopt methods according to what they see happening in Java circles are emulating Java. Thus when I say that a particular piece of C++ code emulates a feature of Java, that particular C++ code is doing a poor job (either in speed, code size, bad typing, memory usage, etc. or any combination of the those) of doing what the Java feature does.


OOP doesn''t emulate C++. Or is perhaps Java and Smalltalk trying to emulate C++, too? If you say yes, then you are truly blinded by your C++ devotion.

And then we have this:
"*sigh* But it''s actually not an argument against C++, it''s an argument against the blind adherence to the C standard in the visual studio compiler."
But if bad compilers isn''t an argument against C++, how can it be an argument against Java:
"But C++''s compilers are more mature than the Java ones ( and don''t even get me started on the VM architecture and HUGE errors with thread scheduling, ugh ), which gives C++ the implementation edge."
Or, if you think it IS a valid argument (i don''t), wouldn''t that mean that C wins? After all, C compilers are more mature than both C++ and Java compilers.


You C and C++ programmers never learn... Java is better than both C and C++. C compatibility is annoying. C++ duplicates many of C''s features (there are fstreams and there are FILEs, which one should I use? Are FILEs really C++?)...
And operator overloading isn''t such a good idea... how do you multiply two vectors?

Vector A(2.f, 4.f, 5.f), B(4.f, 2.f, 5.f);
cout << A*B << endl;


Hmm, what results does this produce? Well, you never know... might print the dot product, but it might as well print the cross product.
Language wars are stupid... but they can be fun, too.

- Frosty
Hmm...where do I even start? I''d best go in order.


EvilTwin: You''re right, he was talking about what you do with your fingers on a keyboard. My apologies both to the author (whom I now know most certainly understands something about data types) and anyone who was misled by my comment.

(BTW, I have seen programmers who think data types are a bother.)


MadKeithV: I was not saying that all member functions need "this" pointers, or anything remotely related to that. The article mentioned needing the convenience of the implicit "this" pointer, and I was pointing out the only way to get it.

(Looking at it later, I think the trouble is that C static functions and C++ static member functions are two very different things.)


Now we have a problem...there seems to be at least two different anonymous posters, as one signs his/her /Siigon, another doesn''t sign a name, and the third one uses /frosty. So I''ll just use the two names given and ask all the anonymous posters to please find the correct argument.


Anonymous Poster: Check out the term C++. To non-C/C++ coders here, I understand it to mean the "next iteration of C." There were some necessary corrections to the language syntax. The examples you gave are from ANSI C''s compatibility with K&R C, and although C++ is compatible with ANSI C syntax, it does not support the K&R C syntax. You might as well have cited this difference (which I heard has been eliminated from C code):


void function()
int x;
int y;
{
}



#include "multi-page rebuttal of C++ makes big projects harder"

(meaning I''ll add it later tonight, if I get the time)


Regarding your argument of overloaded operators, they are not syntactic sugar - the operator implementations for each data type are quite clearly defined in the standard. Same operators (+, -, *, /, <<, etc.), different implementation. That''s operator overloading. C does operator overloading. It would be ludicrous to you think the existence of different data types doesn''t require operator overloading. I think what you really mean is that user-defined operator overloading (which is what C++ supports over C) is bad. That''s just plain denial. Look at 3D matrix math, and tell me the mathematical definition of the matrix data type doesn''t require overloaded operators.


Regarding the properties of the sets of numbers, that can be found in any algebra text. I''m not here to explain the fundamental principles of algebra - just the C++ implementation of them.

quote: Excerpt from Algebra 2, Lesson A, section D, page 8-9

Understanding algebra is easier if we make an effort to remember the difference between properties and definitions. A property describes the way something is. We can''t change properties. We are stuck with properties because they are what they are. For instance,

3 + 2 = 5

and

2 + 3 = 5

The order of addition of two real numbers does not change the answer. We call this property the commutative property of real numbers in addition. "

Definitions are different because they are things that we have agreed upon. For instance,

3^2

means

3 times 3

It didn''t have to mean that. We could have used 3^2 to mean 3 times 2, but we didn''t. We note that the order of operations is also a definition. When we write

3 + 4 * 5

We could mean to multiply first or to add first. Since we cannot have two different answer to the same problem, it is necessary to agree on the meaning of the notation. We have agree to do multiplication before algebraic addition, and so this expression represents the number +23.

Also, when we wish to write the negative of 3^2, we write

-3^2

When we wish to indicate that the quantity -3 is to be squared, we write

(-3)^2

These are definitions of what we mean when we write

-3^2

and

(-3)^2

and there is nothing to understand. We have defined these meanings to have the meanings shown.



If you''ll notice the wording in the very first paragraph of the excerpt, you''ll see that the commutative property belongs to the set of real numbers. Operators are just something that humans have defined: a definition.


Regarding the definition of Object-Oriented programming, data encapsulation is an essential principle. It''s the whole driving principle behind objects, really, or they wouldn''t be objects. That''s why terms other than Object-Oriented exist: procedural(using all globals), structural (using data structures with procedures), object-based (using objects which have responsibility and support messaging, but are not polymorphic), and object-oriented (object-based, but with the addition of polymorphism and thus inheritance). Defining new types requires that those types be responsible for their internal memory usage (a small part of data encapsulation), which requires destructors.

Another fundamental property of objects is messaging, or what is sometimes called active data structures. The classes need to be bound together in one coherent class (another essential principle). I can cite articles to this effect, if you like.


Regarding strong typing, need I say anything at all? This has to be about the silliest argument in programming. The whole of programming is manipulating data. Thus, data typing is one of the most important features in the language. Mixing learning the language''s casting with learning algorithms is an obvious recipe for disaster. Not knowing the language while trying to write algorithsm would be equally disastrous. Your argument is like saying that power saws are stupid and useless because in the hands of a minor they might hurt someone.


frosty: Sorry to burst your argument (and it''s a good one, btw), but if you''ll re-read my post, I was talking about the use of the language by a particular type of people, and not the language design. Structural code is really just emulating OOP, etc. because people think in objects. There are probably more advanced paradigms than OOP, like perhaps generic programming. But each previous paradigm builds on the design of the previous set. Don''t tell me OOP was possible without the idea of functions (procedural programming). One comes before the other, and they progress, but they are really modeling the human thought processes.

Comparing Java to C++ would be kind of neat, but I don''t really know Java. I''m not a C++ "zealot," unless you call using what you currently know is most efficient being blind. If something better comes up, I''ll switch. But C is not better (and that''s the basic argument here).




- null_pointer
Sabre Multimedia
Just to clear up something, the article under discussion was a rant I wrote because I was frustrated with some coworkers who felt that C++ was the be-all and end-all of languages. I didn''t show the rant to them. I left it up on my personal web page for people who knew me or were reading about me to read.

Some people (including those coworkers, and certain people here) are convinced that C++ is in all (or almost all) ways good, and the purpose of the rant is not to dissuade those people. Rather, it is aimed at people who sit on the fence. It attempts to address the assumption that more features is better (despite the potential costs in terms of using other people''s code and the costs to compiler development) and the notion that since C++ is effectively C with more, it is therefore strictly superior to C, etc.

I''ve used other, more "pure" OOPLs, like Smalltalk. I find that those languages let me work in a different paradigm, to approach problems on an entirely different level. C++, however, does not feel that way to me. C++ feels like a kludgish attempt to bring classes to C, and lots of hacking and complexity growth to try to make it all work somewhat sanely (but only somewhat: e.g. virtual functions during constructors). Did we really NEED references AND pointers? Did we really NEED five (I think) different ways for a call site to dispatch? etc. etc.

I will grant you this: if you want to bring OOP to C, C++ is probably about as good an attempt as any (although I wonder if not using C''s linker could have led to a design that didn''t require exposing private members in the public class definition). But I just found it amusing that on reading "Design and Evolution" at the suggestion of many people, I found out exactly why I didn''t like it: because instead of trying to write "the best possible" language (from the point of view of how good the code is, how easy it is to do things), Stroustrop tasked himself with making a POPULAR ("successful") language. Hence the C compromise in the first place, and hence lots of design decisions that followed on, which I think make it a worse language than it could have been. Of course, had it not been C compatible, it would just be another OOPL footnote or another Python, and nobody would be debating it.

If you love C++, great, more power to you, have fun. As others have said, the point is to use whatever tool works best. The situation that motivated that rant was me having to work with other people who coded everything in C++ as much as possible (actually, in COM to get better interface support), code which was perfectly well written stylistically but in my experience harder to understand. That may, of course, be a comment about me; but hopefully the arguments can stand or fall on their own merits.

I read through the first bit of null_pointer''s long reply, but after seeing the ad hominem bits mixed in, and a response to my compiler-performance-issues comment that amounted to "you are wrong" with no argument or justification, I punted it.

Sean Barrett

This topic is closed to new replies.

Advertisement