Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Features of C++ that can't be implemented in C?

Tags:

c++

c

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?
like image 734
Sachin Chourasiya Avatar asked Dec 01 '09 11:12

Sachin Chourasiya


2 Answers

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 (opaque 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."

like image 89
sharkin Avatar answered Sep 20 '22 15:09

sharkin


How about RAII and templates.

like image 45
Nick Dandoulakis Avatar answered Sep 19 '22 15:09

Nick Dandoulakis