What Separates C++ From C? | C++ Programming

UPI Study › Courses › C++ Programming › Free lessons › Lesson 2.1 Free with a free account

What Separates C++ From C?

C++ Programming · Chapter 2: Getting Started with C++Section 2.1 · lesson 8 of 84video coming soon

← How C++ Came to BeNext lesson: Preparing Your Machine →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

A near-subset, plus facilities for larger programs.

  • Describe how C and C++ overlap and differ
  • Name what C++ adds and the C problem behind each
  • Weigh what near-compatibility buys and costs
  • Recognize valid C that C++ rejects

Transcript

Everything said in the video, section by section (1,725 words). Read along, or search it.

Opening Question

C++ Grew Out of C

If you can already read C, what's actually different about C++? C++ didn't replace C. It grew out of it, keeping almost all of it, and adding facilities on top. That explains why anyone who knows C can read C++ on sight, and why the same job can often be done two ways. It also explains why some perfectly correct C habits count as poor practice here. Treat this as a map, not a tutorial. Each item is introduced just far enough to recognize, and taught properly later.

Core Idea

Most Valid C Is Valid C++

Most valid C is also valid C++. Hand a working C program to a C++ compiler, and it very likely compiles and behaves the same. Every arithmetic operator, every control structure, pointers, arrays, structs, the preprocessor and the C library are all still here. On top of that, C++ adds classes, references, overloading, namespaces, a real bool, new and delete, streams, templates, and stricter checking. The word near matters, though. A thin sliver of valid C is deliberately rejected, so the overlap is very large, but not total. The honest one-line description: C++ is C, plus facilities for organizing larger programs, plus a compiler that checks more of what you wrote.

Overview

The Whole Difference at a Glance

Here's the whole difference at a glance. In C, a struct holds data, and the functions live elsewhere, with nothing protecting the data. A C++ class carries its own data and operations. To let a function change a caller's variable, C passes an address. C++ offers references. C needs a unique name per function, so absolute value becomes abs, labs and fabs. Overloading lets them share one name. C's global names collide, so libraries prefix everything. Namespaces keep them apart. C carries truth in integers. C++ has a real bool. Malloc hands out untyped bytes, while new knows the type. Printf trusts a format string, while streams work out the types themselves. And code that should work for many types becomes one template.

Framework

Grouping Additions by the Job They Do

A flat list is hard to remember. It's more useful to group the additions by the job they do. Some organize larger programs: classes and objects, namespaces, templates, and the standard library. Some catch mistakes earlier: stronger type checking, a real bool, typed allocation, and type-aware input and output. And some let you write less, more readably: references, overloading, operators on your own types, and ready-made containers.

Sub-topic

Classes Bundle Data With Operations

Start with classes. In C, a struct holds fields and nothing else. The functions that work on them live elsewhere, tied only by a naming convention. Any code anywhere can reach in and change any field. So a rule like, the balance must never go negative, can't be enforced in one place. Everyone who touches the struct has to respect it. A C++ class puts the data and the operations in one definition, and lets you say which parts outsiders may see. Here, balance is hidden, and deposit is public.

Code Example

The Compiler Refuses Private Access

Here's a complete version. Deposit only accepts positive amounts, so the rule lives inside the class. Now try to reach in from outside, and set the balance directly, the way any C code could. The compiler refuses: balance is a private member of Account. Outside code must go through the operations you provided, so the rule lives with the data it protects. Most of what people mean by object-oriented programming, constructors, inheritance and virtual functions, follows from this one change, and comes later.

Sub-topic

References Replace Pointer Ceremony

Next, references. C has one way to let a function change something its caller owns: pass the address, and work through the pointer. That works, but pointer syntax spreads through the function body, and a pointer can be null or uninitialized, so careful code checks it. A reference is another name for an object that already exists. It's attached when it's created, can't be pointed elsewhere later, and uses plain syntax. So the C++ version of twice reads like ordinary code, and the call passes v itself, not its address. Quick check. v starts at 21, and is passed to both functions. What does the program print? It prints 84: 21 doubled to 42 through the pointer, then to 84 through the reference. Same effect both ways. The reference just says it with less ceremony.

Sub-topic

Overloading Lets Functions Share a Name

Overloading solves a different C annoyance. A C function name must be unique. So absolute value appears as abs for int, labs for long, and fabs for double. Use the wrong one, and it still builds, with the wrong answer. C++ lets functions share a name if their parameter lists differ. At each call, the compiler examines the arguments, and picks the version that fits. Here, one name handles an int and a double.

Sub-topic

Namespaces Keep Global Names Apart

Every global name in a C program shares one space. Two libraries that both define init can't be used together without a fight. The traditional defense is a prefix on every public name, like gfx init and net init. It works, but it's only a convention. A namespace is a named region that names can live inside. Two libraries can each define init, and your code says which one it means. The entire standard library lives in a namespace called std, which is why its names are written std, colon colon, cout.

Sub-topic

A Real Bool Type

C represents truth with integers: zero is false, and anything else is true. But nothing in int found tells a reader whether it's a count, a code, or a yes-or-no answer. In C++, bool is built in, with exactly two values: true and false. The old integer style still compiles, but here it's treated as a lapse, not a style.

Sub-topic

Typed Allocation With New and Delete

C's malloc deals in raw bytes. You calculate how many you need, it returns an untyped pointer, and you convert it to the type you meant. The memory contains whatever was there before. C++ adds new and delete, which know about types. New is told what to create, not how many bytes, so the size is computed for you. Crucially, new also runs the type's setup, and delete runs its cleanup before releasing the memory. That matters enormously once your types manage resources of their own. And the two routes must never be crossed. Memory from new is released by delete, and memory from malloc by free.

Sub-topic

Streams Work Out Types Themselves

With printf, the types are announced in a format string, and the values arrive separately. Nothing guarantees the two agree. Write percent d, which promises an int, and pass a double. The behavior is undefined: garbage, or worse. Clang does warn about this call. But it's only a warning. The program still builds. C++ streams take each value directly, and work out its type from the value itself. There's no format string to keep in sync. And your own types can be taught to print once, then used everywhere. Printf still works, but new code is expected to prefer streams.

Sub-topic

Templates and the Standard Library

Suppose you need a list of integers, and later a list of strings. In C, every option is unattractive. Write the whole thing twice. Write it once with void pointers and cast at every use, losing type checking. Or generate it with unreadable macros. A template lets you write the definition once, with the type left as a parameter. Ask for a list of ints, and the compiler makes one, fully checked. Because templates exist, C++ ships a large library built on them, often called the STL. Growable arrays, lists, maps and sets, plus sorting, searching and counting: already present, tested, and typed.

Stricter Checking

Compile Errors Instead of Runtime Hunts

C++ is less willing than C to assume you meant something reasonable. Conversions C performs quietly are refused, at compile time. C silently converts an untyped pointer to any pointer type. C++ refuses, which is one reason new is preferred over malloc. C historically let you call a function before declaring it, guessing its signature. C++ requires a declaration first. C lets integers flow freely into enumerated types. C++ doesn't do that automatically. And in C, an empty parameter list means unspecified, so anything is accepted. In C++, it means no parameters, so passing any is an error. Each is a mistake C would reveal at run time, often far from the fault. A compile error is a one-second message, instead of a day-long hunt.

Edge Cases

Valid C That C++ Rejects

Finally, the thin sliver: valid C that a C++ compiler won't accept. You don't need to memorize these. Just know they exist. As C, this file builds, with only a warning. Compile the same text as C++, and it stops. Assigning malloc's untyped result to an int pointer, without a cast, is an error. Using new as a variable name is an error, because new is a keyword. So is class. A string literal into a writable char pointer: the standard forbids it, and Clang flags it, as a warning by default. And calling a function declared with empty parentheses, with arguments, is an error, because empty means no parameters. Going the other way, the gap is much bigger. A C compiler rejects almost any C++ that uses classes, references, overloading, namespaces or templates.

Trade-offs

The Costs and Benefits of Compatibility

Keeping C almost intact inside C++ was a deliberate trade, with real benefits and real costs. It buys direct use of enormous amounts of existing C code. It costs you a choice: most jobs have two accepted solutions. Your C skills transfer at once. So do your C habits, including the poor ones. Code that works can still be poor C++. A team can move a large program across gradually, but then it mixes two memory models and two input and output systems. And low-level control is fully kept, along with C's hazards: uninitialized memory, buffer overruns, and undefined behavior.

Good Practice

Prefer the C++ Way by Default

So form this habit now. Because both toolsets are legal, it compiled and ran can't be your standard. In new code, prefer the C++ way by default, and reach for the C way only when something specific requires it.

Key Takeaways

Summary and a Question to Consider

To summarize. Almost all C is valid C++, and a thin sliver is refused. The additions organize larger programs, catch mistakes earlier, and let you write less, more readably. New and delete run a type's setup and cleanup, while malloc and free deal in raw bytes, and the two are never mixed. And because both toolsets are legal, prefer the C++ one in new code. Something to think about: a colleague says printf and malloc both work in C++, so there's no reason to learn the alternatives. Give two reasons that's a weak position.

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About What Separates C++ From C?

Is C code also valid C++, and how do the two languages differ?
Most valid C is also valid C++, but C++ is more than a copy of C. It keeps C's operators, control structures, pointers, arrays, structs, preprocessor, and library. It then adds classes, references, overloading, namespaces, a real bool, new and delete, streams, templates, and stricter checking. A working C program very likely compiles as C++, though a thin sliver is rejected.
What does C++ add to C, and what C problem does each addition solve?
Each major C++ addition targets a specific C problem. Classes bundle data with operations, where a C struct leaves its fields unprotected. References replace pointer syntax for changing a caller's variable. Overloading lets functions share one name instead of abs, labs, and fabs. Namespaces prevent global name collisions. A real bool replaces integers as truth values. New knows types where malloc returns raw bytes, streams replace printf format strings, and templates replace duplicated code.
Is there valid C code that a C++ compiler rejects?
Yes, a thin sliver of valid C is rejected by C++ compilers. Assigning malloc's result to an int pointer without a cast, as in int *p = malloc(sizeof(int)); is an error in C++. So is using a C++ keyword as a name, such as int new = 5; or a variable called class. Passing a string literal to a writable char pointer is also forbidden, though Clang only warns by default.
What are the benefits and costs of C++ staying almost compatible with C?
Near-compatibility lets C++ use enormous amounts of existing C code, and C skills transfer immediately. The cost is a choice: most jobs have two accepted solutions, such as printf or streams, and poor C habits still compile. Gradual migration mixes two memory models and two input and output systems. C's hazards also remain, including uninitialized memory, buffer overruns, and undefined behavior. In new code, prefer the C++ way by default.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →