The C++ Language

The C++ Language

C++ was designed to provide Simula’s facilities for program organization together with C’s efficiency and flexibility for systems programming.

C++ Features

Classes
User-defined types
Operator overloading
Attach different meaning to expressions such as a + b
References
Pass-by-reference function arguments
Virtual Functions
Dispatched depending on type at run time
Templates
Macro-like polymorphism for containers (e.g., arrays)
Exceptions

Example: A stack in C

typedef struct {
char s[SIZE];
int sp;
} Stack;
stack *create() {
Stack *s;
s = (Stack *)malloc(sizeof(Stack));
s->sp = 0;
return s;
}
Creator function ensures stack is created properly.
Does not help for stack that is automatic variable.
Programmer could inadvertently create uninitialized stack.
char pop(Stack *s) {
if (sp = 0) error(“Underflow”);
return s->s[–sp];
}

void push(Stack *s, char v) {
if (sp == SIZE) error(“Overflow”);
s->s[sp++] = v;
}
Not clear these are the only stack-related functions.
Another part of program can modify any stack any way it wants to, destroying invariants.
Temptation to inline these computations, not use functions.

C++ Solution: Class

class Stack {
char s[SIZE];
int sp;

public:

Stack() { sp = 0; }
void push(char v) {
if (sp == SIZE) error(“overflow”);
s[sp++] = v;
}
char pop() {
if (sp == 0) error(“underflow”);
return s[–sp];
}
};

Cours gratuitTélécharger le cours complet

Télécharger aussi :

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *