Differences between C and C++#
In this section, we will look at the most important differences between the two languages.
Definition#
C is a structural programming language, so everything is broken into functions that get the work done. C does not support objects and classes.
C++, however, supports procedural and object-oriented programming paradigms. It focuses on using objects and classes.
In C++, it is impossible to have a field named class
, as it is a reserved keyword.
Exception Handling#
C uses functions for error handling. C++ has well-designed try-catch blocks that make debugging a lot easier.
File Extensions#
All C programs are saved with a .c
extension. C++ uses the .cpp
extension.
Variables#
In C, need to declare all variables at the beginning of the function block. In C++, the variables can be declared anywhere as long as they are declared before used in the code.
Data Types#
With C, you can define your own type using struct
, union
, or enum
.
// Structures
struct stud_id
{
char name[20];
int class;
int roll_number;
char address[30];
};
C++ supports user-defined data types as well. C++ user-defined data types include:
// Classes
class <classname>
{
private:
Data_members;
Member_functions;
public:
Data_members;
Member_functions;
};
// Structures
struct stud_id
{
char name[20];
int class;
int roll_number;
char address[30];
};
// Unions
union employee
{
int id;
double salary;
char name[20];
}
// Enumerations
enum week_days{sun, mon, tues, wed, thur, fri, sat};
int main()
{
enum week_days d;
d = mon;
cout << d;
return 0;
}
//Typedef
typedef <type> <newname>;
typedef float balance;
Strings#
C represents string literals using char[]
. In C++, strings are objects of the class string, defined in the header file <string>
. This is how strings are represented in C: