What is the history of struct/class in C++? - c++

I'm taking a class on Object Oriented Programming in C++. In a recent assignment I defined a member function within a struct. My instructor explained that, although it's compilable to use member functions within structs, he would prefer we didn't, for backward compatibility with C, and (especially in this beginner class) to practice good data encapsulation- we should use a struct for types that contain mostly data, and a class for applications that benefit from more procedural encapsulation. He indicated that this practice comes from the history of structs/classes in C++, which is what I'd like to know more about.
I know that structs are functionally the same as classes except for default member/inheritance access. My question is:
Why are structs AND classes included in C++? From my background in C#, where structs and classes have important differences, it seems like struct in C++ is just syntactic sugar for defining classes with default public-ness. Is it?
I'm not looking for opinions on when/why one should be used instead of the other- I was born well after these constructs were, and I'm looking for the history of them. Were they conceived together? If so, why? If not, which came first, and why was the second added? I realize that there are many venerable elders within this community who may have living memory of these features' origins, and links to standards publications, or examples of code, where both, one, or the other first appeared, will add to answers' helpfulness.
Please note, this question is not:
What are the differences between struct and class in C++?
C++ Structs with Member Functions vs. Classes with Public Variables
Can C++ struct have member functions?
nor Function for C++ struct

To ease development of polyglot headers.
C and C++ are separate languages, but the C++ language is designed to provide a large useful common subset with the C language. Several commonly used constructions in the C++ language have the same meaning (or nearly so) as they have in the C language. In the case of struct, the C++ language defines it as syntactic sugar for class that approximates the behavior of a struct in the C language, namely that members are public by default. Thus a program or part thereof can be written in this common subset. This allows, for example, a library to provide a single header file that declares the same API to both programs written in the C language and programs written in the C++ language.
Some differences between the C language and the C++ language are listed in a question that has since been closed as too broad. From the perspective of somebody programming in this common subset language, these differences can be treated as "implementation-defined behavior", where compilers for the C language produce one behavior and compilers for the C++ language produce the other.
In fact, the C++ standard provides mechanisms to aid development of polyglot programs that are valid in both C and C++ languages. The extern "C" linkage specifier allows a program to be written partly in C and partly in C++. And the __cplusplus symbol is used in #ifdef __cplusplus conditions to conditionally enable macros, linkage specifiers, and other specifics that only one of the two languages is supposed to see.

In the old days (late 1980s or early 1990s), a C++ compiler (then called cfront) translated C++ code to C code. That C++ was widely different from current C++11 or C++14 (or even old C++03).
I don't remember the details, but it could have happened that struct at that time was parsed completely, but passed unchanged into the generated C code, while class was preprocessed to something different (and was translated to a struct).
I might be completely wrong, this is from my human memory, and I only used (on SunOS3, Sun3/160 workstations) a couple of times that cfront. It left me unimpressed, but interested. At that time, the translation to C code added a significant time to the build process. But things have changed a lot, translating to C makes a lot of sense today...
(In those days, a hello world program in Ada took 5 minutes to compile, and with cfront it might be 3 minutes, but in C it was less than a minute)
Later on, the definition of C++ changed, and struct foo { was indeed equivalent to class foo{ public:, but I am not sure that was the case in the primordial C++ compiler.

Both were included in the original C++ language, but struct long predates C++ in the C language.
C++ includes structs because it inherited them from C. There was no reason to remove them from C++ and break existing C code bases that may be compiled with a C++ compiler.
C++ introduces class as a new keyword. Presumably the keyword was introduced to provide the option of differentiating newly created C++ classes from existing structs in legacy C code bases.

C++ is mostly a superset of C. So (mostly) if you can do something in C you can do it in C++. Structs are a C feature and were included in C++. Refer to this for the reasons C++ isn't a true superset: Where is C not a subset of C++?

Related

Which languages will call C++ with no explicit bridging?

While developing a new product, we decided to go for a mix of C++ and C#, haven been told that bridging them to allow the C# code to call the C++ code would be easy (spoiler, it's not).
We're pretty experienced C++ programmers and not at all C# programmers so we pretty much just had to believe what we've read. A few attempts to call C and Objective-C was promising and we even found a few articles that showed how to make an unmanaged C++ class available in C# -- or at least we thought. The C++ code in the articles, wasn't C++, but instead the horrible monster C++/CLI that Microsoft seems to think is C++. Since we're doing the C# stuff to get some bits "for free" in macOS and Windows, C++/CLI isn't an option either :-(.
Anyway, plenty of people have claimed that it's easy to call C++ code from some specific programming language, but so far, I haven't seen a single one that will allow me to do so (I haven't been paying too much attention to this, so please provide me with an obvious example). C++ invariably always means C with no C++ stuff at all; no namespaces, classes, no stl, lambdas or anything. Just plain dumb C.
So, are there any languages, besides C++(/CLI) that will allow me to do the following:
Create an instance of a class, using a C++ constructor, and dispatch it with a C++ destructor.
Call member functions on an object ( foo f; f.foo();) with a C++ class.
Use std::vector, std::find_if, std::string and other stuff from the stl. Complete coverage of the stl is not required.
Use overloaded functions (i.e. f(), f(int), f(std::string))
Use overloaded operators (foo operator + (foo, foo))
Use C++11, C++14 and/or C++17 features.
Use RAII (rather important IMHO).
Use namespaces.
No. There is no such language.
Unless you count Objective-C++. But that falls pretty much in the same bucket as C++/CLI, in being C++ with some extensions. And C++/CX is another such beast.
There are some interop tools that can work with C++ classes (SWIG for example), but I have never heard of a tool that is capable of instantiating C++ templates (like vector or find_if) on demand.
What languages will call C++ with no explicit bridging?
The short answer to this question is: NONE
Remember that a programming language is a specification written in some technical report, usually in English. For examples, read n1570 (the spec of C11) or R5RS (the spec of Scheme). For C++, see n3337.
Actually, you are interested in implementations, e.g. in compilers and interpreters for your programming languages. These implementations are practically software. And then the answer might become: it depends (notably on the ABI used & targetted by your compiler and system).
See for examples this list of ABIs for Linux.
plenty of people have claimed that it's easy to call C++ code from some specific programming language,
The C calling conventions are quite common, and it might help to declare every C++ function callable from outside as extern "C". But there is no silver bullet, and details matter a lot.
So, are there any languages, besides C++(/CLI) that will allow me to do the following:
list of C++ features skipped
Probably not.
You probably need at least to understand more about memory management approaches. I recommend understanding more about garbage collection, e.g. by reading the GC handbook (at least for underlying concepts & terminology). Learn more about foreign function interfaces (in some cases, the libffi might help) and language bindings.
You might also consider generating some of the C++ or C glue code, maybe with SWIG (or write your own C++ glue code generator).
On operating systems providing dynamic linking capable of loading plugins at runtime (e.g. Linux with dlopen(3)/dlsym(3); but other OSes often have similar facilities) you could even consider generating some C or C++ glue code at runtime in some temporary file, compile it as a temporary plugin, and dynamically loading that plugin. You could also consider JIT-compiling libraries like GCCJIT or LLVM (or libjit).
I recommend reading SICP, the Dragon Book, and probably Lisp In Small Pieces. Of course, learn something about OSes, e.g. Operating Systems: Three Easy Pieces. Reading about Linkers and Loaders could also help.
As an excellent example of cleverly gluing C++, look into CLASP and see this video.
But whatever approach you take, you'll need a lot of work (years, not weeks).
C++ as a language does not have a defined ABI (Application Binary Interface) - which basically means that there is no universal standard of what a C++ class/function call/template would look like in binary form on any given platform, or across platforms.
What that means is that there is no universal way to call C++ code from other languages, on different platforms, or even across compilers on the same platform. It also means that the people who are telling you "it's easy to call C++ code from XYZ language" are mostly incorrect (or at least incredibly incomplete).
Where there are interfaces it's either because the provider of the interface controls the ABI (C++/CLI with .NET), or because there is a translation layer from C++ to something like the C calling convention (Boost::python).
Some work has been done towards attempting to define an ABI per-platform (http://open-std.org/JTC1/SC22/WG21/docs/papers/2014/n4028.pdf), but as far as I'm aware it has not yet been accepted into C++17.
You can look into using C++ interpreter, which allows for the fine-grained control you ask for. But I don't know of any that "just works", see also:
Have you used any of the C++ interpreters (not compilers)?

What does "Objective-C is a superset of C more strictly than C++" mean exactly?

From what i read there: Why is Objective-C not very popular outside of the Apple community?
Objective-C is a superset of C (much more strictly than C++, in fact) so the issue of backward compatibility does not arise. Anything you can do in C you can do in Objective-C.
Being a superset is binary, like being pregnant. Obj-C is a superset of C, and C++ is not.
What do they mean by superset? In what way does objective-C would be more close//backward compatible to C? In what way does objective-C follow the C philosophy more closely than C++?
Can any C program be compiled without modification by a objective-C compiler (100% compatibility)?
This is more a question about programming language design and compatibility than a wars about which one is better.
I prepared a simple diagram; it is not very pretty, but hopefully gets the point across:
Red: the set of all programs valid in C, C++, and Objective-C (relatively small)
Green: the set of all programs valid in C and Objective-C, but invalid in C++ (even smaller)
Gray: the set of all programs valid in Objective C and C++, but invalid in C (empty, as far as I know)
Blue: the set of all programs valid only in Objective C (relatively large)
Yellow: the set of all programs valid only in C++ (largest)
The set of valid C programs (in red and green) is an strict subset of the set of valid Objective C programs (blue)
What do they mean by superset?
They mean strict superset. Any valid C program will compile with an Objective-C compiler. Some valid C programs will not compile with a C++ compiler.
In what way does objective-C would be more close//backward compatible to C?
Here's a simple example:
int *foo = malloc(12);
Compiles in C and Objective-C, but not in C++. There are, of course, other examples as well.
In what way does objective-C follow the C philosophy more closely than C++?
All - Objective-C is a strict superset of C.
Can any C program be compiled without modification by a objective-C compiler (100% compatibility)?
Yes.
From the ground up, C++ has been designed as a "better C", fixing design omissions, both real and perceived, as the authors of C++ went through the language. The result of this design decision has been that X being a valid C program did not guarantee that X would compile, let alone run, when processed by the C++ compiler. The changes touched such basic constructs as string literals (they became const char*), assignment of void pointers, conversions between enums and integral types, semantics of compound assignment operators, and so on.
Moreover, once C99 came along, features that made it into the updated C standard were left out from the updated C++ standard. Again, very important language features were left out - most notably, designated initializers and variable-size arrays.
In contrast, Objective C has been positioned as a superset of C, requiring all valid C programs to be compilable with an Objective C compiler.
"Objective-C is a superset of C" means that every valid C program is a valid Objective-C program (with the same meaning).
It is sometimes said, although not by C++ experts, that C++ is a superset of C. This isn't accurate, which is why your quotation is making a big deal of comparing the two.
Objective C is a set of backward-compatible extensions to C. This is possible because the Objective C features are delimited in two very simple ways:
use of the character #. This character is not currently used in the C language.
a simple syntactic extension for invoking methods, [obj method:argument]. In C, square brackets are used in a very specific way for array subscripting, and so this is invalid C syntax. Extensions which build on invalid syntax do not change the meaning of anything that is valid in the host language.
So easy to see that no program which uses Objective C extensions can be a strictly conforming ISO C program, no matter how simple. Moreover, every ISO C program can be declared, by definition, to be a valid Objective C program. Objective C can easily follow developments like C99 and C11.
On the other hand, C++ is not simply extensions to C; it is a different language which changes the meaning of some of the syntax of C. C++ and C are separately maintained, and so their relationship changes over time. For instance, C has acquired new features that are completely absent in C++, and quite likely will not go into C++, such as C99 variable-length arrays. C++ cannot easily pick up new C features.
If you write a portable C program, it should be at the same time an Objective C program.
But additional care will be needed so that it is also a C++ program with the same meaning. (This practice is not unheard of, and the dialect it requires is informally known as "Clean C").
A trivial example of a C program that breaks when treated as C++ is any C program which uses a C++ keyword as an identifier, such as class or virtual. Objective C does not introduce any reserved keywords. It has new keywords that are introduced by the # character, like #interface.

correct me if my understanding of c++ is wrong

correct me if any of my following current understanding of c++ is wrong:
C++ is an extended version of C. Therefore, C++ is just as efficient as C.
Moreover, any application written in C can be compiled using C++ compilers
C syntax is also valid C++ syntax
C++ is at the exact same language level hierarchy as C.
Language Level Hierarchy
eg. lowest-level: assembly language,
high-levels: Java, PHP, etc
so my interpretation is that
C++/C is at a lower level than Java,PHP etc since it's closer to hardware level (and therefore because of this,it's more efficient than Java, PHP, etc), yet it is not as extreme as assembly language....but C++/C is at the same level with each other and neither one is closer to hardware level
If you start with code that's legal as both C and C++, it will typically compile to the same result with both, or close enough that efficiency is only minimally affected.
It's possible to write C that isn't allowable as C++ (e.g., using a variable with a name that's the same as one of the key words added in C++, such as new). Most such cases, however, are trivial to convert so they're allowed in C++. Probably the most difficult case to convert is code that uses function declarations instead of prototypes (or uses functions without declarations at all, which was allowed in older versions of C).
See 2 -- some syntactical C won't work as C++. As noted, it's usually trivial to convert though.
No, not really. Although C++ does provide the same low-level operations as C, it also has higher-level operations that C lacks.
C++ is at the exact same language level hierarchy as C.
Language Level Hierarchy
eg. lowest-level: assembly language, high-levels: Java, PHP, etc
Programming languages are often categorised from 1st generation (machine code), 2nd generation (assembly language), 3rd generation (imperative languages), 4th generation (definition's a bit vague - domain-specific languages intended for high productivity, e.g. SQL), 5th generation (typical language of the problem expression, e.g. maths notation, logic, or a human language; Miranda, Prolog). See e.g. http://en.wikipedia.org/wiki/Fifth-generation_programming_language and its links.
In that sense, C and C++ are both 3rd generation languages. (As Jerry points out, so are PHP, Java, PERL, Ruby, C#...). Using that yardstick, these languages belong in the same general group... they're all languages in which you have to tell the computer how to solve the problem, but not at a CPU-specific level.
In another sense though, C++ has higher level programming concepts than C, such as Object Orientation, functors, and more polymorphic features including templates and overloading, even though they're all ways to organise and access the steps for solving the problem. Higher level languages (i.e. 5GL) don't need to be told that - rather, they just need a description of the problem and knowing how to solve the entire domain of problems they find a workable approach for your specific case.
C++/C is at a lower level than Java,PHP etc since it's closer to hardware level (and therefore because of this,it's more efficient than Java, PHP, etc), yet it is not as extreme as assembly language....but C++/C is at the same level with each other and neither one is closer to hardware level
This is confusing things a bit. Summarily:
C++ and C do span lower than Java/PHP, yes.
C++ and C do tend to be more efficient, yes. You can get a general impression of this at http://benchmarksgame.alioth.debian.org/u64q/which-programs-are-fastest.html - don't take it too literally, it depends a lot on your problem space.
C++ and C both go as low as each other, but C++ has some higher level programming support too (though it's still a 3GL like C).
Let's look at a few examples:
bit shifting: Java is designed to be more portable (sometimes at the expense of performance) than C or C++, so even with JIT certain operations might be a bit inefficient on some platforms, but it may be convenient that they operate predictably. If you're doing equivalent work, and care about the edge cases where CPU behaviours differ, you'll find C and C++ leave operator behaviour for the implementation to specify. You may need to write multiple versions of the code for the different deployment platforms, only to end up getting pretty much the same performance as Java (but programs often know they won't exercise edge cases, or don't care about the behavioural differences). In that respect, Java has abstracted away a low-level concern and could reasonably be considered higher level but pessimistic.
C++ provides some higher level facilities such as templates (and hence template metaprogramming), and multiple inheritance. Compilers commonly provide low level facilities such as inline assembly and the ability to call arbitrary functions from other objects/libraries as long as the function signatures are known at compile time (some libraries work around this limitation). Interpreted (e.g. PHP) and Virtual Machine based (e.g. Java) languages tend to be worse at this.
Java also provides some higher level facilities that C++ lacks - e.g. introspection, serialisation.
Generally, I tend to conceive of C++ spanning both lower and higher than Java. Put another way, Java overlaps a section in the middle of C++'s span. But, Java has a few stand-out high-level features too.
PHP is an interpreted language that again abstracts away some low level concerns, but generally fails to provide good facilities for more abstract or robust programming techniques too. Like most interpreters, it does allow run-time evaluation of arbitrary source code, as well as run-time modification of class metadata etc., which allows a high level, powerful but dangerously unstructured approach to programming. That kind of thing isn't possible in a compiled language unless the compiler is shipped in the deployment environment (and even then there are more limitations).
C++ is an extended version of C. Therefore, C++ is just as efficient as C.
Generally true.
Moreover, any application written in C can be compiled using C++ compilers
C syntax is also valid C++ syntax
There are some trivial differences, e.g.:
in C++, main() must have return type int and implicitly returns 0 on exit if not return statement's encountered, but C allows void or int and for the latter must explicitly return an int
C++ has additional keywords (e.g. mutable, virtual, class, explicit...) that are therefore not legal C++ identifiers, but are legal in C
Still, your conception is essentially true.
1/4 and 2/3 seem to be saying very similar things, but:
Yes (Depends on what you mean by "extended", but at a broad level, yes)
Not always
Not always
Yes
Moreover, any application written in C
can be compiled using C++ compilers
Not every C program can be compiled using a C++ compiler. There are some differences between C and C++ (keywords, for example), that prevent mixing C and C++ in some ways. Stroustrup adresses some important points in C and C++: Siblings.
C++ is an extended version of C.
Therefore, C++ is just as efficient as
C.
That depends on the language features you use. I heard that using OOP might bring more cache misses than using a more C-like approach. I can't tell wether this is true or not, as I didn't read more on that subject. But it might be something which should be considered. This is only one example were performance isn't easy comparable.
This isn't exactly true, beyond extra C++ language features that are slower, there are different optimizations that can be done that will change this. Due to the better C++ type system, these are actually normally in C++'s favor however.
No, a big case is that C++ doesn't support automatic cast from void* so for instance
char* c = malloc(10); // Is valid C, but not C++
char* c = (char*)malloc(10) //Is required in C++
Except for C99 and newer C features, I think this is nearly always the case. Keep in mind this is only taking into account syntax this doesn't mean that everything that can compile in C can also compile in C++.
Could you elaborate on what you mean by this, what do you mean by "language level hierarchy"?
Summary:
True.
Dangerously false.
False.
Subjective
Some examples for 2/3:
sizeof 'a' is 1 in C++ and sizeof(int) in C.
char *s = malloc(len+1); is correct C but invalid C++.
char s[2*strlen(name)+1]; is valid (albeit dangerous) C, but invalid C++.
sizeof (1?"hello":"goodbye") issizeof(char *)` in C but 6 in C++.
Attempting to compile existing C code as C++ is simply invalid and likely to produce dangerous bugs even if you hunt down and "fix" all the compile-time errors. And writing code that's valid in both languages is perhaps a reasonable entry for a polyglot competition, but not for any serious use. The intersection of C and C++ is actually a very ugly language that's the worst of both worlds.
Your understanding is wrong in some of your points:
1) your first point is right.C++ is an extension of c.
2) second point is right . C can be compiled using c++ compilers.
3) Some of C syntax varies from c++. In c++, using structure , c should specify structure name but c++ it is not mandatory to specify structure name.Also C++ have the concept of class that is not available in c. C++ also have higher security mechanisms.
4)C is procedural language but c++ is object oriented approach. so c++ is not at the exact same language level hierarchy as c.
C language is not a subset of C++ lanaguage. Check the C99 spec for example - it will not compile in C++ compiler easily. However most of C89 source code can be copied&paste to C++ source code.
C and C++ are languages that can be implemented with "zero overhead" comparing to bare iron.
No. But most of C++ compilers are C compilers too. It means that you can compile .C and .C++ files using the same toolchain.
No, The evolution of these languages differs. See answer to question 1.
C++ is multiparadigm language. Yes, it can be used in the same way as C. But it can be used as DSL too - it provides greater abstraction level.
That's a whole big question to answer.
Not in all cases!
not true because of 3
not true
They are not exactly the same
I don't think language level hierarchy matters too much for a thing. For example, C is a high-level one compared to assembly language while it's a low-level one compared with Java/C#.

Is Objective-C++ a totally different language from Objective-C?

As the title says... are they considered different languages? For example if you've written an application using a combination of C++ and Objective-C++ would you consider it to have been written in C++ and Objective-C, C++ and Objective-C++ or all three?
Obviously C and C++ are different languages even though C++ and C are directly compatible, how is the situation with Objective-C++ and Objective-C?
From: https://en.wikipedia.org/wiki/Objective-C#Objective-C.2B.2B
Objective-C++ is a front-end to the GNU Compiler Collection, which can compile source files which use a combination of C++ and Objective-C syntax. Objective-C++ adds to C++ the extensions Objective-C adds to C. As nothing is done to unify the semantics behind the various language features, certain restrictions apply:
A C++ class cannot derive from an Objective-C class and vice versa.
C++ namespaces cannot be declared inside an Objective-C declaration.
Objective-C classes cannot have instance variables of C++ classes which do not have a default constructor or which have one or more virtual methods, but pointers to C++ objects can be used as instance variables without restriction (allocate them with new in the -init method).
C++ "by value" semantics cannot be applied to Objective-C objects, which are only accessible through pointers.
An Objective-C declaration cannot be within a C++ template declaration and vice versa. However, Objective-C types, (e.g., Classname *) can be used as C++ template parameters.
Objective-C and C++ exception handling is distinct; the handlers of each cannot handle exceptions of the other type.
Care must be taken since the destructor calling conventions of Objective-C and C++’s exception run-time models do not match (i.e., a C++ destructor will not be called when an Objective-C exception exits the C++ object’s scope). The new 64-bit runtime resolves this by introducing interoperability with C++ exceptions in this sense
Objective-C++ simply allows Objective-C and C++ code to be mixed (with caveats). It's not really a language on its own so much as a mechanism for allowing the two languages to intermix.
C and C++ are not directly compatible. Neither is a superset of the other (though most C is valid C++). Objective-C is a strict superset of C, and Objective-C++ is a strict superset of C++. Those are the only statements you can make (except trivially reversing it).
It's hard to answer this question confidently without understanding what definition of "different language" you want to apply.
Objective-C is a superset of C: it adds some additional syntax on top of the C language. Objective-C++ is a superset of C++ in the same way.
C and C++ are actually different languages. Although C++ is designed to be compatible, there is some C that is not valid C++, and vice versa.
So, I'd say, yes, Objective-C++ is a different language from Objective-C, because C++ is a different language from C. However, I wouldn't call them totally different.
At first glance, using the Objective-C++ dialect looks like a straightforward approach. It is the result of mashing C++ and Objective-C together in the same compiler, and robust implementations exist in GCC and now clang. Considering just how different the details of Objective-C and C++ are, the GCC hackers have done a great job of it. But as you start renaming your .m files to .mm to introduce chunks of C++, you quickly realise it's not quite so simple.
Header files and the C preprocessor in general have caused headaches for C, C++ and Objective-C programmers for decades. It gets worse when you try to mix the languages. Say you wanted to use the STL's map in an Objective-C class in your project. Apple's Foundation libraries to my knowledge don't contain a sorted, tree-based map; one of our StyleKit Components needs exactly that, for example. So we simply create an instance variable for the map in our class and away we go:
#include <map>
#interface MyClass : NSObject {
#private
std::map<int, id> lookupTable;
}
// ...
#end
However, std::map [2] only makes sense to a C++-aware compiler, and only after an #include [3], so this header now can only be #imported from Objective-C++ files. Any code using this class now needs to be converted to Objective-C++ itself, and importing from other headers leads to a cascade effect that quickly encompasses the whole project.
In some cases, this may be acceptable. However, switching a whole project or large parts of it across just to introduce a library which is used in one location is not only excessive; if you're the only one who knows C++ on a project with multiple Objective-C programmers, you might find this to be an unpopular idea. It might also cause issues in the same way that compiling pure C code with a C++ compiler rarely is completely hassle-free. Moreover, it means that code isn't automatically reusable in other Objective-C projects.
So it's always better not to mix up unless it's so important
To know more about strategies for using objective c++ in objective c and vice versa click here
Objective-C is probably the official term that you would put in a resume.
Objective-C++ is not really a new language, it just specifies a few things that allow Objective-C code to co-exist with C++ code. Saying your app was written in Objective-C and C++ or just Objective-C++ is probably what you want. Putting all of Objective-C, Objective-C++, C++ is redundant.

Is it true that there is no need to learn C because C++ contains everything? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features. However, some others have told me that this is not necessarily true. Can anyone shed some light on this?
Overview:
It is almost true that C++ is a superset of C, and your professor is correct in that there is no need to learn C separately.
C++ adds the whole object oriented aspect, generic programming aspect, as well as having less strict rules (like variables needing to be declared at the top of each function). C++ does change the definition of some terms in C such as structs, although still in a superset way.
Examples of why it is not a strict superset:
This Wikipedia article has a couple good examples of such a differences:
One commonly encountered difference is
that C allows implicit conversion from
void* to other pointer types, but C++
does not. So, the following is valid C
code:
int *i = malloc(sizeof(int) * 5);
... but to make it work in both C and
C++ one would need to use an explicit
cast:
int *i = (int *) malloc(sizeof(int) * 5)
Another common portability issue is
that C++ defines many new keywords,
such as new and class, that may be
used as identifiers (e.g. variable
names) in a C program.
This wikipedia article has further differences as well:
C++ compilers prohibit goto from crossing an initialization, as in the following C99 code:
void fn(void)
{
goto flack;
int i = 1;
flack:
;
}
What should you learn first?
You should learn C++ first, not because learning C first will hurt you, not because you will have to unlearn anything (you won't), but because there is no benefit in learning C first. You will eventually learn just about everything about C anyway because it is more or less contained in C++.
While it's true that C++ was designed to maintain a large degree of compatibility with C and a subset of what you learn in C++ will apply to C the mindset is completely different. Programming C++ with Boost or STL is a very different experience than programming in C.
There was a term of art called using C++ as a better C. This meant using some C++ language features and tools to make C programming easier (e.g., declaring the index variable of a for loop within the for statement). But now, modern C++ development seems very different from C other than a great deal of the syntax and in those cases the C legacy often seems to be a burden rather than a benefit.
It might be true that you don't need to learn the syntax of C if you know the syntax of C++ but you cetainly do need to learn of how coding practices are different in C than in C++.
So your professor wasn't 100% right.
In C you don't have the classes to arrange your code into logical modules and you don't have C++ polymorphism. Yet you still need to achieve these goals somehow.
although the syntax of C is to some extent a subset of C++, programming in C is not a subset of programming in C++. it is completely different.
Yes and no.
As others have already answered, the language C++ is a superset of the language C, with some small exceptions, for example that sizeof('x') gives a different value.
But what I don't think has been very clearly stated is that when it comes to the use of these two languages, C++ is not a superset, but rather different. C++ contains new (it can be discussed if they are better) ways of doing the basic things, such as writing to the screen. The old C ways are still there, but you generally use the new ways. This means that a simple "hello world" program looks different in C and in C++. So it is not really true that the simple things are the same in C and C++, and then you just add more advanced stuff, such as support for object-oriented programming, in C++.
So if you have learnt C++, you will need to re-learn quite a lot before you can program in C. (Well, it is possible to teach C++ as an extension to C, still using printf and malloc instead of iostreams and new, and then adding classes and other C++ things, but that way of using C++ is generally frowned upon.)
No C++ isn't really a superset of C. You can check this article for a more extensive list of the differences if you're interested:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
Not entirely true.
The biggest "gotcha" is typing -- C++ is much more strongly typed than C is, and the preferred methods for solving this in C++ are simply not available in C. Namely, you can silently cast between types in C (particularly pointer types), but not in C++. And C++ highly recommends using the static_cast/reinterpret_cast/const_cast methods for resolving these issues.
More importantly, if you learn C++ syntax and mannerisms, you'll probably find it difficult to deal with C (some may say this is good; and I prefer C++ myself, but sometimes it just isn't an option, or you have to deal with legacy code that's in C and not C++). Again, the most likely issues you'll encounter are dealing with pointers (particularly char*'s and general array usage; in C++ using std::string and std::vector or other collections is simply better).
It's certainly possible to learn C++, and then learn the differences between C and C++ and be capable of programming in both. But the differences are far more than just skin deep.
It is true that for most purposes, C++ contains everything that C does. Language lawyers will be quick to point out that there are some very special edge cases that are valid C but not valid C++.
One such example might be the C declaration
int virtual;
which declares an integer named "virtual". Since "virtual" is a keyword in C++, this is not valid C++.
There is a large common core of C (especially C89) and C++, but there are most certainly areas of difference between C and C++. Obviously, C++ has all the object-oriented features, plus the generic programming, plus exceptions, plus namespaces that C does not. However, there are also features of C that are not in C++, such as support for the (close to archaic) non-prototype notation for declaring and defining functions. In particular, the meaning of the following function declaration is different in C and C++:
extern void function();
In C++, that is a function that returns no value and takes no parameters (and, therefore, is called solely for its side-effects, whatever they are). In C, that is a function which returns no value but for which there is no information about the argument list. C still does not require a declaration in scope before a function is called (in general; you must have a declaration in scope if the function takes a variable list of arguments, so it is critical to #include <stdio.h> before using printf(), etc).
There are also differences:
sizeof('c')
In C++, the answer is 1; in C, the answer is normally 4 (32-bit systems with 8-bit characters) or even 8 (64-bit systems with 64-bit int).
In general, you can write code that will compile under both C and C++ compilers without much difficulty - the majority of my code does that all the time. The exceptions are either a result of carelessness on my part, or because I've consciously exploited the good features of C99 that are not in C++ 98, such as designated initializers, or long long.
Stroustrup himself advices against learning C first. But then again, he (and many others of his generation) managed to become a C++ guru starting from C.
I personally would disagree with your professor.
Generally speaking, C++ is based on C and in that "sense" contains it and extends it.
However, since traditionally people learned C and only then the extensions of C++, your professor's statement is incorrect since to use C++ correctly you would need to master the C origins. It is possible that when teaching you something, your professor or textbook will not specifically mention what came from which language.
In addition, it is important to understand that despite the similarities, not every C program runs in the same way under C++. For example, C structs are interpreted differently (as classes with everything public) by the C++ compiler.
When I teach, I teach the C core first, and then go to C++.
If any of the students in the class intend to become embedded software engineers, then they may have no choice but to program in C (see this question, and this one, among others).
Of course, having learnt C++, it may be less of a transition for them than starting from scratch - but it still makes your professor's statement untrue!