tags:

views:

621

answers:

14

I have read that C++ is super-set of C and provide a real-time implementation by creating objects. Also C++ is closed to real world as it is enriched with Object Oriented concepts.

What all concepts are there in C++ that can not be implemented in C?

  1. Some say that we can not over write methods in C then how can we have different flavors of printf()? For example printf("sachin"); will print sachin and printf("%d, %s",count ,name); will print 1,sachin assuming count is an integer whose value is 1 and name is a character array initililsed with "sachin".
  2. Some say data abstraction is achieved in C++, so what about structures?
+3  A: 
  1. There is only one printf() in the C standard library. Other varieties are implemented by changing the name, for instance sprintf(), fprintf() and so on.

  2. Structures can't hide implementation, there is no private data in C. Of course you can hide data by not showing what e.g. pointers point to, as is done for FILE * by the standard library. So there is data abstraction, but not as a direct feature of the struct construct.

Also, you can't overload operators in C, so a + b always means that some kind of addition is taking place. In C++, depending on the type of the objects involved, anything could happen.

Note that this implies (subtly) that + in C actually is overridden; int + int is not the same code as float + int for instance. But you can't do that kind of override yourself, it's something for the compiler only.

unwind
printf("Sachin") will print only sachin, whereas print("count %d , %s",count,name) will print 1 sachin. Dont you think its a form of overwritting methods with varying number of arguments passed
Sachin Chourasiya
@unwind: FILE* is pretty damn private if you ask me. OO is a coding technique, not a language feature.
DrPizza
No, because it's not typesafe like method overloading. If you pass the wrong number of arguments it can crash.
Jason Orendorff
@Sachin Chourasiya: No.
DrPizza
@Sachin: No I don't, all calls to printf() will lead to the same entrypoint, in which the code will inspect its first argument (the format specifier string) and read additional arguments as required. It's just a function doing things depending on its arguments, the compiler isn't jumping to different functions based on the arguments. So no.
unwind
@DrPizza, could you please justify the No
Sachin Chourasiya
@Sachin Chourasiya: I'm surprised it needs justification. Since the same function gets called regardless of the number of parameters passed, it is clearly not comparable in effect to overloading.
DrPizza
Performing different tasks by using variable number of arguments resembles method over loading. Isnt it?
Sachin Chourasiya
@Sachin: printf just uses `...` (ellipses) to indicate a variable number of arguments. It's totally different from function overloading. You can easily write your own function that uses this. See http://en.wikipedia.org/wiki/Stdarg.h
Charles Salvia
@Charles, Thanks for the link
Sachin Chourasiya
@DrPizza: If you define OO as the usual trinity of encapsulation, inheritance and polymorphism, then it *is* a language feature because encapsulation is enforced by the compiler in OO languages.
Charles Salvia
A: 

There shouldn't be too much such things, because early C++ compilers did produce C source code from C++ source code. Basically you can do everything in Assembler - but don't WANT to do this.

ziggystar
Some compilers still convert into C (I believe comeau does), but there is no direct translation. Templates, and in particular template deduction, SFINAE is processed by the C++ compiler prior to converting into C. Once the actual code is known, the compiler can inject it, but you cannot manually fake it in C.
David Rodríguez - dribeas
+2  A: 

printf is using a variable length arguments list, not an overloaded version of the function

C structures do not have constructors and are unable to inherit from other structures they are simply a convenient way to address grouped variables

C is not an OO langaueage and has none of the features of an OO language

having said that your are able to imitate C++ functionality with C code but, with C++ the compiler will do all the work for you in compile time

Alon
@Alon, I agree with Inheritence, but what about overloading?
Sachin Chourasiya
Please note that ellipsis (variable number of arguments) isn't neccesarily supported on all platforms.
sharkin
@RA, Could you please name some where I am restricted to use only one version of print
Sachin Chourasiya
C not being an OO language doesn't mean you can't do OO programming with it, you just need to implement all the 'syntactic sugar' the OO language provides yourself, things like v-tbls, operator overloading, etc.
Skizz
I agree with Skizz, printf() is the standard example
Sachin Chourasiya
@Skizz good comment I agree, I modified my answer :-)
Alon
@Sachin Chourasiya : function overloading was not implemented in C, you can do it if your are using a C++ compiler to compile C code , but that's sort of cheating ...
Alon
@Sachin: On platforms where you can't use ellipsis there's usually a special printf-like function provided. The thing to remember is that when you see a function declared like this( arg, ... ), i.e with the three dots, you should know that it might not be portable.
sharkin
Thanks RA, I got it
Sachin Chourasiya
Varargs and overloading are different things. A function that takes varargs can take any number of arguments of any type (in C, in C++ you cannot pass non-POD), but the code being executed is one and only one.
David Rodríguez - dribeas
+2  A: 

All the rest is "easily" faked :)

pmg
-1, you have a point but you should decorate such a claim with arguments. Faking polymorphism is one thing, but I can't see how you'll do RAII, overloading by argument list or complex cast to name a few. Yeah sure you can do anything in assembler or microcode, but the question at hand is not about what your processor is capable of
sharkin
First C++ compilers were actually translators into C, so you can fake pretty much everything.
n0rd
Ultimately you can translate everything to a turing machine and code in BrainFuck.But that's not an "easy" faking.
Tristram Gräbener
What's so hard about faking namespaces? `MyNameSpace_function() ;`
Clifford
E.g. scoped `using` directives.
Georg Fritzsche
@Clifford: Oh Clifford...
sharkin
+3  A: 

Well, if you aren't going to implement a C++ compiler using C, there are thousands of things you can do with C++, but not with C. To name just a few:

  • C++ has classes. Classes have constructors and destructors which call code automatically when the object is initialized or descrtucted (going out of scope or with delete keyword).
  • Classes define an hierarchy. You can extend a class. (Inheritance)
  • C++ supports polymorphism. This means that you can define virtual methods. The compiler will choose which method to call based on the type of the object.
  • C++ supports Run Time Information.
  • You can use exceptions with C++.

Although you can emulate most of the above in C, you need to rely on conventions and do the work manually, whereas the C++ compiler does the job for you.

kgiannakakis
Yes I do agree theres alot in C++ that could not be implemented in C like virtual functions, friend etc but there are many which could be achived in C. Some where we might heard that we can not overwrite a methiod in C and thats true if tried in user code , but I am amazed to see printf() standard function.
Sachin Chourasiya
@Sachin: You can fake virtual functions in C.
sharkin
@Sachin: printf is not an overload, it is a single unique function taking varargs.
David Rodríguez - dribeas
+11  A: 

How about RAII and templates.

Nick D
+1 In my opinion this is the strength of C++.The object oriented stuff is nice, but not as important.
Tristram Gräbener
Yes there are points where C++ win over C
Sachin Chourasiya
@Sachin: To win you need to compete in the same sport as the looser.
sharkin
You can do RAII with macros in C. Templates, is really more tricky.
Bluebird75
@Bluebird: Please describe how you would do that.
sharkin
A: 

One feature that isn't really OOP-related is default arguments, which can be a real keystroke-saver when used correctly.

Mark Rushakoff
That would be the easiest to fake (if you had overloads) just implement a function with one less argument and do it calling the other function with the default value. Now, the real problem is not default arguments, but not having overloads.
David Rodríguez - dribeas
A: 

Function overloading

TanvirK
@Tanvirk, that fakely could be achieved by ellipses. printf() is the standard example
Sachin Chourasiya
@Sachin; it would be really difficult to use ellipses to fake function overloading, because you wouldn't necessarily be able to tell what *type* of arguments were passed to the function. The `printf` family of functions has the advantage of a format-string which specifies, in order, the type of each argument.
Charles Salvia
+1  A: 

What all concepts are there in C++ that can not be implemented in C?

This is somewhat of an odd question, because really any concept that can be expressed in C++ can be expressed in C. Even functionality similar to C++ templates can be implemented in C using various horrifying macro tricks and other crimes against humanity.

The real difference comes down to 2 things: what the compiler will agree to enforce, and what syntactic conveniences the language offers.

Regarding compiler enforcement, in C++ the compiler will not allow you to directly access private data members from outside of a class or friends of the class. In C, the compiler won't enforce this; you'll have to rely on API documentation to separate "private" data from "publicly accessible" data.

And regarding syntactic convenience, C++ offers all sorts of conveniences not found in C, such as operator overloading, references, automated object initialization and destruction (in the form of constructors/destructors), exceptions and automated stack-unwinding, built-in support for polymorphism, etc.

So basically, any concept expressed in C++ can be expressed in C; it's simply a matter of how far the compiler will go to help you express a certain concept and how much syntactic convenience the compiler offers. Since C++ is a newer language, it comes with a lot more bells and whistles than you would find in C, thus making the expression of certain concepts easier.

Charles Salvia
The contents are well written, one point about reference, we can have a reference to a structure in C as we have to class in C++
Sachin Chourasiya
You can't have a reference in C, you can only have a pointer. (Although under the hood they are basically the same thing.)
Charles Salvia
+18  A: 

Some responders here argues that most things that can be produced with C++ code can also be produced with C with enough ambition. This is true in some parts, but some things are inherently impossible to achieve unless you modify the C compiler to deviate from the standard.

Fakeable:

  • Inheritance (pointer to parent-struct in the child-struct)
  • Polymorphism (Faking vtable by using a group of function pointers)
  • Data encapsulation (private sub structures with an implementation not exposed in public interface)

Impossible:

  • Templates (which might as well be called preprocessor step 2)
  • Function/method overloading by arguments (some try to emulate this with ellipses, but never really comes close)
  • RAII (Constructors and destructors are automatically invoked in C++, so your stack resources are safely handled within their scope)
  • Complex cast operators (in C you can cast almost anything)
  • Exceptions

Worth checking out:

  • GLib (a C library) has a rather elaborate OO emulation
  • I posted a question once about what people miss the most when using C instead of C++.

Clarification on RAII:

This concept is usually misinterpreted when it comes to its most important aspect - implicit resource management, i.e. the concept of guaranteeing (usually on language level) that resources are handled properly. Some believes that achieving RAII can be done by leaving this responsibility to the programmer (e.g. explicit destructor calls at goto labels), which unfortunately doesn't come close to providing the safety principles of RAII as a design concept.

A quote from a wikipedia article which clarifies this aspect of RAII:

"Resources therefore need to be tied to the lifespan of suitable objects. They are acquired during initialization, when there is no chance of them being used before they are available, and released with the destruction of the same objects, which is guaranteed to take place even in case of errors."

sharkin
I think this is debatable; it depends on what you mean by "implement". You can "implement" the effect of RAII in C by manually calling initialization and destructor functions. The difference is that the compiler won't automatically do it for you. But how is that different from polymorphism, which you included under the "fakeable" category? The C compiler won't help you out with the V-table either, or the pointer to parent-struct you need to place in every class.
Charles Salvia
@Charles: Yes it's debatable. The administration of inheritance and polymorphism is not a feature of polymorphism itself in C++. However, RAII is by definition a concept about implicit resource management. So I would say that constructor-like and destructor-like idioms can be achieved in C, but you'll never have RAII.
sharkin
+1 for the most important part of RAII: EVEN IN CASE OF ERRORS.
Tobias Langner
This is a good list. I'd argue dynamic_cast could be faked in C by writing conversion functions for the casts you need. In theory, all of these can be done in C, if you're willing to put in the work. After all, they are both Turing-complete languages.
Adrian McCarthy
@Adrian: Fair enough about dynamic casting, but I really can't accept the argument about anything is possible with enough work. It's irrelevant. With enough work I can rebuild my toyota to drive under water with 15 passengers, but then it's not a toyota anymore.
sharkin
Exceptions seem to be fakeable with an exception stack data structure and use of `setjmp`/`longjmp`.
caf
+2  A: 

It is less about what features can't be implemented, and more about what features are directly supported in the language, and therefore allow clear and succinct expression of the design.

Sure you can implement, simulate, fake, or emulate most C++ features in C, but the resulting code will likely be less readable, or maintainable. Language support for OOP features allows code based on an Object Oriented Design to be expressed far more easily than the same design in a non-OOP language. If C were your language of choice, then often OOD may not be the best design methodology to use - or at least extensive use of advanced OOD idioms may not be advisable.

Of course if you have no design, then you are likely to end up with a mess in any language! ;)

Clifford
+2  A: 

You can implement C++ fully in C... The original C++ compiler from AT+T was infact a preprocessor called CFront which just translated C++ code into C and compiled that.

This approach is still used today by comeau computing who produce one of the most C++ standards compliant compilers there is, eg. It supports all of C++ features.

Tony Lambert
... but the C code generated is no doubt far less attractive.
Clifford
I'm not sure about that compilers break code down to common primitive components of code which are then optimised. Whether from C, C++ or indeed other languages these can end up with very similar results. A good C compiler produces better code than most people can by hand these days.
Tony Lambert
A: 

Quoting Joel, I'd say a powerful "feature" of C++ is operator overloading. That for me means having a language that will drive you insane unless you maintain your own code. For example,

i = j * 5;

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it. And i might be of a type that has operator= overloaded, and the types might not be compatible so an automatic type coercion function might end up being called. And the only way to find out is not only to check the type of the variables, but to find the code that implements that type, and God help you if there’s inheritance somewhere, because now you have to traipse all the way up the class hierarchy all by yourself trying to find where that code really is, and if there’s polymorphism somewhere, you’re really in trouble because it’s not enough to know what type i and j are declared, you have to know what type they are right now, which might involve inspecting an arbitrary amount of code and you can never really be sure if you’ve looked everywhere thanks to the halting problem (phew!).

When you see i=j*5 in C++ you are really on your own, bubby, and that, in my mind, reduces the ability to detect possible problems just by looking at code.

But again, this is a feature. (I know I will be modded down, but at the time of writing only a handful of posts talked about downsides of operator overloading)

lorenzog
-1, not because of the opinion/rant per se, but because it's offtopic for this question. At best, it's a comment to another answer.
MSalters
Completely off-topic, and I'd take `a = b + c * d;` over `a = voegen(b, vermenigvuldigen(c, d));` any day (it's Dutch to me) ;)
UncleBens
A: 

I suppose there are so many things namespaces, templates that could not be implemented in C.

Sachin Chourasiya