POO TEORIE SUMARIZATA

Page 2:

  • Functions can have default values for one or more parameters

  • Default values ar

    Unknown

    e specified in the function definition

  • Default values are usually specified in the prototype

Page 3:

  • Example of a function with a default value for a parameter

  • The default value is specified in the prototype

  • The function can be called with or without specifying the value for the default parameter

Page 4:

  • Dynamic memory allocation in C++

  • Example of allocating and deallocating memory using new and delete

  • Example of allocating and deallocating memory for an array using new[] and delete[]

Page 5:

  • Reference type in C++

  • A reference is like an implicit pointer to an object

  • Example of declaring and using a reference

  • A reference must be initialized when declared

Page 6:

  • Introduction to programming

  • Definition of a programmer and an informatician

  • The goal of programming is to solve problems

Page 7:

  • Example of using a reference to modify a variable

  • Incrementing a reference increments the value it refers to

Page 8:

  • Different approaches to solving a problem

  • The definition of "better" depends on the context

  • Examples of different priorities in different domains

Page 9:

  • Example of using a reference to assign a new value to a variable

  • Once initialized, a reference cannot be changed to refer to a different object

Page 10:

  • Rules and limitations of using references

  • References must be initialized when defined

  • Null references are not allowed

  • References cannot be used to create arrays

  • References cannot refer to bit fields

Page 11:

  • General observations about parameter passing in functions

  • Formal parameters are created when entering a function and destroyed when returning

  • Pass by value makes a copy of the argument, modifications to the parameter do not affect the argument

  • Pass by reference copies the address of the argument, modifications to the parameter affect the argument

  • Functions can be used as operands in expressions

Page 12:

  • Introduction to object-oriented programming (OOP)

  • Main concepts used in OOP: objects, classes, inheritance, encapsulation, polymorphism, templates

Page 13:

  • Definition of a class in C++

  • A class defines attributes and methods

  • Useful for encapsulation and code reuse through inheritance

Page 14:

  • Definition of an object in OOP

  • An object is an instance of a class with a specific state and behavior

  • Objects have an interface (actions) and a hidden part (state)

  • Objects are grouped into classes, which have similar properties

  • A program in OOP is a collection of objects that interact with each other through messages

Page 15:

  • Main concepts of Object-Oriented Programming (POO):

    • Encapsulation: merging data with code in classes for better error localization and problem modularization.

    • Inheritance: ability to extend a class by adding new functionalities.

    • Code reuse.

Page 16:

  • Access specifiers in POO:

    • Public, protected, private.

    • Accessible within the same class: yes for all access specifiers.

    • Accessible in derived classes: yes for public and protected, no for private.

    • Accessible in other classes: yes for public, no for protected and private.

Page 17:

  • Polymorphism in POO:

    • In an inheritance hierarchy, a method can have different implementations at different levels of the hierarchy.

Page 18:

  • Principles of Object-Oriented Programming:

    • Object class

    • Encapsulation

    • Modularity

    • Hierarchy

    • Compile-time and runtime polymorphism

Page 19:

  • Objects in POO:

    • Have state and actions (methods/functions)

    • Have an interface (actions) and a hidden part (state)

    • Grouped into classes with similar properties

    • Interaction between objects through messages (applying a method)

Page 20:

  • Classes in POO:

    • Mention general properties of objects in the class

    • Useful for encapsulation (hiding information)

    • Code reuse through inheritance

    • Define attributes and methods

Page 21:

  • Class declaration:

    • Syntax: class ClassName { // members };

    • Objects instantiate classes

    • Similar to structures and unions

    • Have functions

    • Access specifiers: public, private, protected (default: private)

Page 22:

  • Class declaration (continued):

    • Members can have different access specifiers

    • Can switch between public and private access specifiers

Page 23:

  • Class example:

    • Syntax: class ClassName { // members };

    • Members can be public or private

    • Example class: employee with name and wage as private members and corresponding getter and setter methods

Page 24:

  • Class restrictions:

    • Prefer the second variant of class declaration

    • Non-static members cannot have initialization

    • Cannot have objects of the class as members (can have pointers to the class type)

    • Cannot use auto, extern, register

Page 25:

  • Instance variables in classes:

    • Data members of the class

    • Generally private

    • Can use public for speed, but not covered in this course

Page 26:

  • Class example with member functions:

    • Example class: stack with init(), push(), and pop() as member functions

    • stck and tos as member variables

Page 27:

  • Defining member functions outside the class:

    • Syntax: return_type ClassName::function_name(parameters) { // function body }

    • Example: defining push() function for stack class

Page 28:

  • Scope resolution operator:

    • :: used to specify the class to which a member function belongs

    • Allows other classes to use the same function names

Page 29:

  • Complete program example using the stack class:

    • Includes the iostream library

    • Defines the stack class with init(), push(), and pop() member functions

    • Defines the main() function that creates two stack objects and performs operations on them

Page 30:

  • Incapsularea

    • Ascunderea de informaţii (data-hiding)

    • Separarea aspectelor externe ale unui obiect care sunt accesibile altor obiecte de aspectele interne ale obiectului care sunt ascunse celorlalte obiecte

    • Defineşte apartenenţa unor proprietăţi şi metode faţă de un obiect

    • Doar metodele proprii ale obiectului pot accesa starea acestuia

Page 31:

  • Incapsularea (ascunderea informatiei) foarte importanta

    • Public, protected, private

    • Accesibilitate în funcție de tipul de membru și relația între clase

Page 32:

  • Incapsularea (ascunderea informatiei) exemplu de cod

    • Clasa Test cu membru privat x

    • Metoda set_x pentru a seta valoarea lui x

    • Accesarea membrului x prin metoda set_x

Page 33:

  • Agregarea (ierarhia de obiecte)

    • Compunerea unui obiect din mai multe obiecte mai simple (relaţie de tip “has a”)

  • Moştenirea (ierarhia de clase)

    • Relaţie între clase în care o clasă moștenește structura și comportarea definită în una sau mai multe clase (relaţie de tip “is a” sau “is like a”)

Page 34:

  • Agregarea exemplu de cod

    • Clasa Profesor cu membri nume și vechime

    • Clasa Curs care conține un obiect de tip Profesor

Page 35:

  • Moștenire

    • Multe obiecte au proprietăți similare

    • Reutilizare de cod

Page 36:

  • Terminologie

    • Clasă de bază, clasă derivată

    • Superclasă, subclasă

    • Părinte, fiu

    • Funcții virtuale, identificare de tipuri în timpul rulării (RTTI)

Page 37:

  • Încorporarea componentelor unei clase în alta

    • Refolosire de cod

    • Detalii mai subtile pentru tipuri și subtipuri

    • Clasă de bază, clasă derivată

    • Clasa derivată conține toate elementele clasei de bază, mai adăugă noi elemente

Page 38:

  • Moștenire exemplu de cod

    • Clasa building cu membri rooms, floors, area și metode set și get pentru acești membri

    • Clasa house derivată din building cu membri bedrooms, baths și metode set și get pentru acești membri

Page 39:

  • Clasa derivată are acces la membrii publici ai clasei de bază și la toți membrii săi (publici și privați)

Page 40:

  • Moștenire exemplu de cod continuare

    • Clasa school derivată din building cu membri classrooms, offices și metode set și get pentru acești membri

Page 41:

  • Implementarea metodelor pentru clasele building, house și school

  • Exemplu de utilizare a claselor house și school în funcția main

Page 42:

  • Polimorfism

    • Polimorfism la compilare și la execuție

    • Exemplu de polimorfism la compilare cu funcția max

Page 43:

  • Functii prieten

    • Accesarea membrilor protected și private din alte clase

    • Utilizate pentru overload-area operatorilor, funcții de I/O și portiuni interconectate

Page 44:

  • Code includes a class called myclass with two private variables a and b

  • set_ab function sets the values of a and b

  • sum function is a friend function of myclass and returns the sum of a and b

  • main function creates an object of myclass, sets the values of a and b, and prints the sum of a and b

Page 45:

  • Code includes two classes C1 and C2 with a private variable status

  • set_status function sets the value of status

  • idle function checks if both C1 and C2 objects have IDLE status and returns 1 if true, 0 otherwise

  • main function creates objects of C1 and C2, sets their status to IDLE, and checks if they are idle

Page 46:

  • Total number of pages in the document is 46

  • The document is from the Faculty of Mathematics and Computer Science at the University of Bucharest

  • The topic is about friend functions in C++

Page 47:

  • Code includes two classes C1 and C2 with a private variable status

  • set_status function sets the value of status

  • idle function is a member function of C1 and checks if both C1 and C2 objects have IDLE status and returns 1 if true, 0 otherwise

  • main function creates objects of C1 and C2, sets their status to IDLE, and checks if they are idle

Page 48:

  • Friend classes have access to private members of the class they are friends with

Page 49:

  • Code includes two classes TwoValues and Min

  • TwoValues class has two private variables a and b

  • Min class is a friend class of TwoValues and has a function min that returns the minimum value between a and b

  • main function creates an object of TwoValues and an object of Min, and prints the minimum value

Page 50:

  • Inline functions are commonly used in classes

  • There are two types of inline functions: explicit (inline) and implicit

Page 51:

  • Code includes an explicit inline function max that returns the maximum value between two integers

  • main function calls the max function and prints the maximum values

Page 52:

  • Inline functions have fast execution and are a suggestion/request for the compiler

  • Inline functions can be very small and can be members of a class

Page 53:

  • Code includes a class myclass with two private variables a and b

  • init function initializes the values of a and b

  • show function prints the values of a and b

  • main function creates an object of myclass, initializes its values, and prints them

Page 54:

  • Code includes a class myclass with two private variables a and b

  • init function initializes the values of a and b

  • show function prints the values of a and b

  • main function creates an object of myclass, initializes its values, and prints them

Page 55:

  • Constructors and destructors are special functions in C++

  • Constructors are used for automatic initialization of objects

  • Constructors have the same name as the class and cannot return values

  • Constructors cannot be inherited but can be called by derived classes

  • Pointers to constructor/destructor functions cannot be used

  • Constructors can have parameters and can be overloaded

  • Destructors are unique and have no parameters

Page 56:

  • Constructors and destructors are used for automatic initialization of objects

  • Objects are not static

  • Constructors have the same name as the class and cannot return values

Page 57:

  • The document is from the Faculty of Mathematics and Computer Science at the University of Bucharest

  • Special characteristics of constructors and destructors are mentioned

  • Constructors have the same name as the class and do not specify a return type

  • Constructors cannot be inherited but can be called by derived classes

  • Pointers to constructor/destructor functions cannot be used

  • Constructors can have parameters (including default parameters) and can be overloaded

  • Destructors are unique and have no parameters

Page 58

  • Constructors of copying:

    • Create an object by taking the corresponding values of another object

    • Implicit existence (bit-by-bit copy, so it needs to be redefined for dynamically allocated data)

Page 59

  • Default constructors:

    • Every class has by default:

      • Default constructor

      • Copy constructor

      • Destructor

      • Assignment operator

  • Parameterized constructors:

    • Arguments in constructors

    • Multiple variants with different numbers and types of parameters can be defined (constructor overloading)

Page 60

  • Example of constructors:

    • Class A with members x, y, and z

    • Main function with object declarations and assignments

Page 61

  • Example of constructors:

    • Class A with a pointer member v

    • Constructor initializes v with dynamic memory allocation

    • Destructor deletes the allocated memory

    • Function afisare takes an object of class A as a parameter

Page 62

  • Example of parameterized constructors:

    • Class A with members x, y, and z

    • Multiple parameterized constructors with different combinations of parameters

Page 63

  • Example of parameterized constructors with default values:

    • Class A with members x, y, and z

    • Constructor with default values for parameters

Page 64

  • Special case of constructor with one parameter:

    • Example code with class X and constructor with one parameter

    • Implicit conversion of data

Page 65

  • Arrays of objects:

    • Directly specify values for constructors with a single parameter

    • Initialize objects in an array with different parameterized constructors

Page 66

  • Example of order of constructor calls:

    • Class A with constructor, destructor, and copy constructor

    • Functions f_cu_referinta and f_fara_referinta

    • Main function with object declarations and function calls

Page 67

  • Order of constructor and destructor calls:

    • Constructors are called in the order of object declarations, destructors in reverse order

    • Global variables are declared before local variables

    • Copy constructor is called when passing an object by value as a parameter

Page 68

  • Example of order of constructor calls:

    • Class A and class B with constructor

    • Object of class A as a member of class B

    • Main function with object declaration

Page 69

  • Example of output:

    • Class A with constructor, destructor, and member functions

    • Function afisare takes an object of class A as a parameter

    • Main function with object declaration and function calls

Page 70:

  • Example of classes and constructors

  • Class cls with a constructor and destructor

  • Class clss with a constructor and destructor

  • Class clss2 with a constructor and destructor

  • main() function creating an object of class clss2

Page 71:

  • Polymorphism in constructors

  • Overloading constructors for flexibility

  • Copy constructors

Page 72:

  • Overloading constructors for flexibility

  • Defining constructors for different initialization modes

  • Compilation error if initialization is attempted in a different way

Page 73:

  • Polymorphism in constructors

  • Importance for dynamic arrays of objects

  • Need for initializing uninitialized objects and initialized objects

Page 74:

  • Polymorphism in constructors

  • Copy constructor issues with object initialization

  • Memory allocation problem when objects share the same memory location

  • Destructor of MyClass frees the same memory twice

Page 75:

  • Copy constructor issues

  • Function call with object as a parameter

  • Function call with object as a return variable

  • Creation of a temporary object and destruction of two objects

Page 76:

  • Use cases of copy constructors

  • Explicit initialization

  • Function call with object as a parameter

  • Function call with object as a return variable

  • Copying using the assignment operator

Page 77:

  • Redefining the copy constructor

  • Multiple parameters with default values

  • Reference parameter

  • Redefining the assignment operator later

Page 78:

  • Example code with a class array

  • Copy constructor implementation

  • main() function demonstrating the use of the copy constructor

Page 79:

  • Observation: copy constructor used only for initialization

  • Copying state between objects may require redefining the assignment operator

Page 80:

  • Table of contents for upcoming topics

Page 81:

  • Static members of a class

  • Static data members distinct for each object

  • Static data members unique for all objects

  • Static keyword for creation, initialization, and access independent of objects

  • Allocation and initialization outside the class

Page 82:

  • Static members of a class

  • Static member functions operate on the entire class

  • Static member functions do not have the keyword "this"

  • Static member functions can only refer to static members

  • Reference to static members: class::member or object.member

Page 83:

  • Common use of static member functions

  • Example code with a class static_type

  • Initialization of static data before object creation

  • Accessing static data through an object

Page 84:

  • Operatorul de rezolutie de scop

    • Exemplu de utilizare: int i; // global i

    • Functia f()

      • Variabila locala i

      • Asignare valorii 10 la i

    • Variabila globala i

    • Functia f()

      • Variabila locala I = 7

      • Asignare valorii 10 la ::i

      • Afisare valorii lui ::I

Page 85:

  • Clase locale

    • Definirea claselor in alte clase sau functii

    • Utilizarea operatorului de rezolutie de scop

    • Rareori utilizate clase in clase

Page 86:

  • Exemplu de clasa in functia f()

    • Restrictii:

      • Functiile definite in clasa nu acceseaza variabilele locale ale functiei

      • Acceseaza variabilele definite static

      • Fara variabile static definite in clasa

Page 87:

  • Functii care intorc obiecte

    • O functie poate intoarce obiecte

    • Un obiect temporar este creat automat pentru a tine informatiile din obiectul de intors

    • Obiectul temporar este distrus dupa ce valoarea a fost intoarsa

    • Probleme cu memoria dinamica: solutie polimorfism pe = si pe constructorul de copiere

Page 88:

  • Returning objects from a function

    • Exemplu de cod

    • Functia f() returneaza un obiect de tip myclass

    • Functia main() atribuie valoarea returnata de f() obiectului o

    • Afisare valorii lui o.get_i()

Page 89:

  • Copierea prin operatorul =

    • Este posibil sa dam valoarea unui obiect altui obiect

    • Obiectele trebuie sa fie de acelasi tip (aceeasi clasa)

Page 90:

  • Supraincarcarea functiilor - observatii finale

    • Folosirea aceluiasi nume pentru functii diferite

    • Functii diferite, dar cu inteles apropiat

    • Compilatorul foloseste numarul si tipul parametrilor pentru a diferentia apelurile

Page 91:

  • Exemplu de supraincarcare a functiilor

    • Doua functii cu acelasi nume, dar cu tipuri diferite pentru parametrul i

Page 92:

  • Numar diferit de parametri

    • Doua functii cu acelasi nume, dar cu numar diferit de parametri

Page 93:

  • Ambiguitati pentru polimorfism de functii

    • Erori la compilare

    • Majoritatea datorita conversiilor implicite

Page 94:

  • Ambiguitati pentru polimorfism de functii

    • Exemplu de cod

    • Eroare la compilare datorita conversiei implicite

Page 95:

  • Ambiguitati pentru polimorfism de functii

    • Problema apare la apelul functiilor

    • Exemplu de cod

    • Ambiguitate la apelul functiei myfunc(10)

Page 96:

  • Ambiguitati pentru polimorfism de functii

    • Ambiguitate intre char si unsigned char

    • Ambiguitate pentru functii cu parametri impliciti

Page 97:

  • Ambiguitati pentru polimorfism de functii

    • Doua tipuri de apel: prin valoare si prin referinta, ambiguitate

    • Mereu eroare de ambiguitate

Page 98:

  • Pointeri catre functii polimorfice

    • Putem avea pointeri catre functii polimorfice

    • Definirea pointerului ne spune catre ce versiune a functiei cu acelasi nume aratam

Page 99:

  • Pointer to function with one parameter

  • Polymorphic variants must match the pointer definition

  • Example code using pointer to function

Page 100:

  • Operator overloading in C++

  • Most operators can be overloaded

  • Overloading also applies to I/O operations

  • Overloading can be done as a member function or non-member function

Page 101:

  • Member functions as operator overloads

  • Operator symbol is used to define the function

  • Unary operators have an empty argument list

  • Binary operators have an argument list with one element

Page 102:

  • Example code for overloading the + operator

  • The function has a single argument because of the "this" pointer

  • The object on the left side of the operator calls the overloaded function

Page 103:

  • Returning the same data type in the operator allows for expressions

  • Example of using the overloaded operator in an expression

  • Temporary object is generated for the expression

Page 104:

  • Overloading the assignment operator

  • Overloading the prefix ++ operator

  • Example code for using the overloaded operators

Page 105:

  • Operator functions are called from the left object for binary operators

  • Assignment operator copies the instance variables and returns *this

  • Multiple assignments can be done from right to left

Page 106:

  • Prefix and postfix forms of operators

  • Example code for prefix and postfix increment operators

Page 107:

  • Overloading +=, *=, etc.

  • Example code for overloading the += operator

Page 108:

  • Restrictions on operator overloading

  • Precedence and number of operands cannot be changed

  • Default values are not allowed, except for ()

  • Certain operators cannot be overloaded

Page 109:

  • Complete decoupling of the original meaning of the operator is possible

  • Inheritance allows for redefining operators in derived classes

Page 110:

  • Operator overloading as friend functions

  • Friend functions can access protected fields

  • Parameters for the function operator include both operands

Page 111:

  • Class loc is defined with two private member variables longitude and latitude.

  • The class has a default constructor and a parameterized constructor.

  • The class has a member function show() that displays the values of longitude and latitude.

  • The class overloads the + operator using a friend function.

  • The class overloads the - operator using a member function.

  • The class overloads the = operator using a member function.

  • The class overloads the ++ operator using a member function.

  • The main() function creates two objects of class loc and performs addition using the overloaded + operator.

Page 112:

  • There are restrictions for operators defined as friends.

  • Operators =, (), [], and -> cannot be overloaded as friend functions.

  • References should be used for overloading ++ and -- operators.

Page 113:

  • Friend functions are used for unary operators ++ and --.

  • References are used to modify the operand.

  • When using pass-by-value, a copy of the object is received and the operand cannot be modified.

Page 114:

  • The class loc is defined with two private member variables longitude and latitude.

  • The class has a default constructor and a parameterized constructor.

  • The class has a member function show() that displays the values of longitude and latitude.

  • The class overloads the = operator using a member function.

  • The class overloads the ++ operator using a friend function.

  • The class overloads the -- operator using a friend function.

  • The main() function creates two objects of class loc and performs increment and decrement operations using the overloaded ++ and -- operators.

Page 115:

  • For the postfix version of ++ and --, an additional parameter int x is added.

  • The postfix version of ++ is defined as a friend function.

Page 116:

  • There may be differences between overloading operators as member functions or friend functions.

  • It is recommended to use member functions when there are no differences.

  • Friend functions are used when there are differences in operand positions.

Page 117:

  • In some cases, two overload functions need to be defined for operators.

  • One function for int + classType and another for classType + int.

Page 118:

  • The class loc is defined with two private member variables longitude and latitude.

  • The class has a default constructor and a parameterized constructor.

  • The class has a member function show() that displays the values of longitude and latitude.

  • The class overloads the = operator using a member function.

  • The class overloads the + operator for loc + int using a friend function.

  • The class overloads the + operator for int + loc using a friend function.

  • The main() function creates three objects of class loc and performs addition using the overloaded + operator.

Page 119:

  • Overloading [] operator must be done as a member function.

  • It cannot be overloaded as a friend function.

  • The operator is considered binary.

  • o[3] is transformed into o.operator[](3).

Page 120:

  • The class atype is defined with a private member array a.

  • The class has a parameterized constructor.

  • The class overloads the [] operator as a member function.

  • The main() function creates an object of class atype and accesses the elements of the array using the overloaded [] operator.

Page 121:

  • The [] operator can also be used on the left side of an assignment.

  • The returned object is then a reference.

Page 122:

  • Array verification can be done using the [] operator.

  • An example is provided in the code.

Page 123:

  • Example of a safe array

  • Class atype with an array a of size 3

  • Constructor initializes the array with values i, j, and k

  • Overloaded operator[] provides range checking for atype

  • If index is out of range, a "Boundary Error" message is displayed and the program exits

  • main function creates an object ob of type atype

  • ob[1] is displayed, which outputs the value at index 1 (2)

  • ob[1] is assigned a new value of 25

  • ob[3] is assigned a value of 44, which generates a runtime error

Page 124:

  • Overloading operator+ for class loc

  • operator+ takes another object op2 of type loc as an argument

  • Creates a temporary object temp

  • Adds the longitude and latitude values of op2 and the current object to temp

  • Returns temp

  • main function creates two objects ob1 and ob2 of type loc

  • ob1.show() displays the longitude and latitude values of ob1

  • ob1(7, 8) is called, which sets the longitude and latitude values of ob1 to 7 and 8 respectively

  • ob1.show() displays the updated values of ob1

  • ob1 = ob2 + ob1(10, 10) adds ob2 and the result of ob1(10, 10) and assigns it to ob1

  • ob1.show() displays the updated values of ob1

Page 125:

  • Handling exceptions in C++

  • An exception is a problem that occurs during program execution

  • C++ exceptions are a response to exceptional circumstances during program execution (allocation problems, division by zero, etc.)

  • Automates error handling

  • try, catch, throw keywords are used

  • try block throws an exception with throw which is caught by catch

  • After catching, execution in the catch block ends and control is passed "upwards", not returning to the point where throw was called

Page 126:

  • Type of argument arg in catch determines which catch block is executed if no exception is generated

  • catch blocks are checked in the order they are written, the first matching type is used

Page 127:

  • Observations about exception handling in C++

  • If throw is used and there is no try block from which the exception was thrown or a function called from a try block: error

  • If there is no matching catch associated with the throw (equal data types), the program terminates with terminate()

  • terminate() can be redefined to do something else

Page 128:

  • Example of handling memory allocation error using exceptions

  • Class TestTry with a pointer v and an integer n

  • Constructor tries to allocate memory using new

  • If allocation fails, a "Allocation Failure" message is displayed and the program exits

  • main function creates an object T of type TestTry

Page 129:

  • Standard library exceptions in C++

  • Examples include std::exception, std::bad_alloc, std::domain_error, etc.

Page 130:

  • Example of throwing and catching exceptions

  • Function Test_Throw_ok throws an exception with the value 10

  • The exception is caught in a catch block with an int parameter and the message "Exception 10" is displayed

  • main function calls Test_Throw_ok

  • Another example is given where the exception is not caught

Page 131:

  • Throwing an exception from a function

  • Class TestTry with a function Test_Throw_Functie

  • Test_Throw_Functie calls a function Test multiple times with different values

  • If the value is less than 0, it throws an exception with the value

  • The exception is caught in a catch block with an int parameter and the value is displayed

  • main function creates an object T of type TestTry and calls Test_Throw_Functie

Page 132:

  • Example of a local try-catch block in a function

  • Class TestTry with a function Test_Try_Local

  • Test_Try_Local declares a variable x and assigns it different values

  • Calls a function Try_in_functie with x as an argument

  • If x is less than 0, it throws an exception with the value

  • The exception is caught in a catch block with an int parameter and the value is displayed

  • main function creates an object T of type TestTry and calls Test_Try_Local

Page 133:

  • Function Exceptii_multiple in C++ handles exceptions

    • If x is less than 0, throws an integer exception

    • If x is equal to 0, throws a character exception

    • If x is greater than 0, throws a double exception

    • If any exception is caught, prints "Catch macar una!"

  • main function calls Exceptii_multiple with different values of x

Page 134:

  • In C++, exceptions can be thrown from base and derived classes

  • If a catch block for the derived class is placed before the catch block for the base class, the catch block for the base class will be executed for an object thrown of the derived class type

  • Example code demonstrates this behavior

Page 135:

  • In C++, a function can specify the types of exceptions it can throw using the throw keyword

  • This restricts the types of exceptions that can be thrown from the function

  • If an unspecified type of exception is thrown, the program terminates

  • The throw; statement can be used to re-throw an exception without specifying the type

Page 136:

  • When defining a function in C++, the list of exception types that can be thrown within the function can be specified

  • This restricts the types of exceptions that can be thrown from the function

  • If an unspecified type of exception is thrown, the program terminates

Page 137:

  • Some compilers may give warnings or terminate the execution when an unhandled exception is thrown

  • The list of exception types can be empty, indicating that no errors are accepted

Page 138:

  • The throw; statement can be used to re-throw an exception without specifying the type

  • Example code demonstrates this behavior

Page 139:

  • Implementation of an exception class hierarchy starting from std::exception

  • C++98 version provides details about <exception> and its member functions

Page 140:

  • Implementation of an exception class hierarchy starting from std::exception

  • Example code demonstrates the usage of a custom exception class

Page 141:

  • terminate() function in C++

  • Example code demonstrates a customized terminate() function

Page 142:

  • Example code with a function f that handles exceptions

  • The program prompts the user for an integer and throws exceptions based on the input

  • The program prints different messages based on the caught exceptions

Page 143:

  • In C++, inheritance is important for code reuse

  • Two ways to achieve code reuse: composition and inheritance

  • Composition involves creating a new class composed of objects representing instances of already created classes

  • Inheritance involves creating a new type of an existing class

Page 144:

  • Example code demonstrating composition in C++

  • Class Y has an embedded object of class X

  • The program accesses the embedded object and modifies its value

Page 145

  • C++ allows inheritance, which means we can derive a class from another base class or multiple classes.

  • Derivation results in new classes called derived classes, which inherit the properties of an already defined class called the base class.

  • Derived classes contain all the members of the base class, along with new members, data, and member functions.

  • A class can be derived from a base class, which in turn can serve as a base class for further derivation, creating a hierarchy of classes.

  • Multiple base classes can be used to define derived classes, incorporating the properties of all the base classes, known as multiple inheritance.

Page 146

  • Syntax for inheritance in C++: class Derived_Class : [access modifiers] Base_Class { ... };

  • The base class is also known as the parent class or superclass, and the derived class is also known as the subclass or child class.

Page 147

  • Example of inheritance in C++.

  • Shows a base class X and a derived class Y that inherits from X.

  • The derived class Y has its own member i and redefines some functions from the base class.

  • Demonstrates the usage of inherited functions and member access.

Page 148

  • Comparison between inheritance and composition.

  • Inheritance allows code to be shared among multiple classes, classes can be extended without recompiling the original classes, and functions using objects from the base class can also use objects from derived classes.

  • Composition is the process of including objects within objects.

Page 149

  • Access modifiers in inheritance.

  • Syntax for access modifiers in inheritance: class A : [access modifier] B { ... };

  • If no access modifier is specified, it is considered implicit private.

  • Member functions in the derived class have access only to the public and protected members of the base class.

Page 150

  • Access modifiers in inheritance.

  • If the access modifier in inheritance is public, the members of the base class retain their access type in the derived class.

  • If the access modifier in inheritance is private, all members of the base class become private in the derived class, regardless of their original access type.

  • If the access modifier in inheritance is protected, the public members of the base class become protected in the derived class, while the rest remain unchanged.

Page 151

  • Example of access modifiers in inheritance.

  • Shows classes Baza, Derivata1, and Derivata2 with different access modifiers.

  • Demonstrates the accessibility of private members in the derived classes.

Page 152

  • Initialization of objects in C++.

  • Importance of ensuring correct initialization in composition and inheritance.

  • Compiler needs to guarantee the invocation of all sub-objects when creating an object.

  • Problem arises when sub-objects do not have default constructors or when default argument values in constructors need to be changed.

  • Solution is a special syntax called the initialization list for constructors.

Page 153

  • Example of initialization list for constructors.

  • Shows class Bar and derived class MyType with an initialization list in the constructor.

Page 154

  • Example 2 of initialization list for constructors.

  • Shows classes Alta_clasa, Bar, and derived class MyType2 with an initialization list in the constructor.

Page 155:

  • Special issue: "pseudo-constructors" for basic types

    • Members of predefined types do not have constructors

    • Solution: C++ allows treating predefined types like a class with a single member and a parameterized constructor

Page 156:

  • Example of composition and inheritance

    • Class X with members i, f, c, and s

    • X constructor initializes members with specific values

    • Main function creates an object of class X and defines variables i and ip

Page 157:

  • Example of inheritance

    • Class A with member i and function f

    • Class B with member i and function f

    • Class C inherits from B and has a member of type A

    • C constructor initializes B and A members

    • C function f redefines the function f from A and calls both A and B functions

Page 158:

  • Constructors of derived class

    • To create an object of a derived class, an object of the base class is created first by calling its constructor, then the specific elements of the derived class are added by calling the constructor of the derived class

    • The declaration of the derived object must contain initialization values for both the specific elements and the base class object

    • This specification is attached to the constructor function of the derived class

Page 159:

  • Constructors of derived class

    • Parameterized constructor example

    • Class Forma with protected member h

    • Class Cerc inherits from Forma and has a protected member raza

    • Cerc constructor initializes Forma member using the Forma constructor

Page 160:

  • Constructors of derived class

    • Copy constructor situations

    • If both the derived class and the base class do not have a defined copy constructor, the compiler creates a default copy constructor that copies member by member

    • If the base class has a defined copy constructor but the derived class does not, the compiler creates a default copy constructor for the derived class that calls the base class copy constructor

    • If a copy constructor is defined for the derived class, it is responsible for transferring the values of the base class members

Page 161:

  • Constructors of derived class

    • Copy constructor example

    • Class Forma with copy constructor

    • Class Cerc inherits from Forma and has a copy constructor that calls the Forma copy constructor

Page 162:

  • Order of calling constructors and destructors

    • Constructors are called in the order of defining the objects as members of the class and in the order of inheritance

    • At each level, the inheritance constructor is called first, then the constructors of the member objects in the respective class (in the order of definition), and finally, the next level in the order of inheritance

    • Destructors are executed in the reverse order of constructors

Page 163:

  • Order of calling constructors and destructors example

    • Classes A, C, B, and D with constructors and destructors

    • D inherits from B and has an object of class A

    • Main function creates an object of class D

    • Order of execution: C B A D ~D ~A ~B ~C

Page 164:

  • Operator=

    • Class Forma with assignment operator

    • Class Cerc inherits from Forma and has an assignment operator that calls the Forma assignment operator

Page 165:

  • Redefining member functions

    • Class Forma with member function afis

    • Class Cerc inherits from Forma and redefines afis by calling the Forma afis function

Page 166:

  • Compatibility between a derived class and the base class

    • Compatibility is valid only for derived classes with public access to the base class

    • Compatibility is one-way, from the derived class to the base class

    • Compatibility is manifested through implicit type conversions:

      • From a derived object to a base object

      • From a pointer or reference to a derived object to a pointer or reference to a base object

Page 167:

  • Importance of inheritance in C++

    • Code reuse

    • Two ways of code reuse: composition and inheritance

    • Composition: the new class is composed of objects representing instances of already created classes

    • Inheritance: a new type is created from an existing class

Page 168:

  • Example of composition

    • Class X with an integer member variable and a set function

    • Class Y with an integer member variable and an embedded object of class X

    • Main function creates an object of class Y and accesses the embedded object

Page 169:

  • Inheritance in C++

    • C++ allows deriving a class from another base class or multiple classes

    • Syntax: class Derived_Class : [access modifiers] Base_Class { ... }

    • Base class is also called the parent class or superclass, and the derived class is also called the subclass or child class

Page 170:

  • Example of inheritance

    • Class X with an integer member variable and various member functions

    • Class Y derived from class X with an additional integer member variable

    • Main function creates an object of class Y and demonstrates the use of inherited and redefined member functions

Page 171:

  • Initialization of objects

    • Important in C++ to ensure correct initialization

    • Applies to both composition and inheritance

    • Compiler needs to guarantee the initialization of all subobjects

    • Special syntax: initialization list for constructors

Page 172:

  • Example of initialization list for constructors

    • Class Bar with an integer member variable

    • Class MyType derived from class Bar with a constructor that calls the base class constructor using the initialization list syntax

Page 173:

  • Example of initialization list for constructors with multiple subobjects

    • Class Alta_clasa with an integer member variable

    • Class Bar with an integer member variable

    • Class MyType2 derived from class Bar with an embedded object of class Alta_clasa

    • Constructor of MyType2 calls the base class constructor and initializes the embedded object using the initialization list syntax

Page 174:

  • "Pseudo-constructors" for built-in types

    • Built-in types do not have constructors

    • Solution: treat built-in types as a class with a single member variable and a parameterized constructor

Page 175:

  • Example of "pseudo-constructors" for built-in types

    • Class X with various member variables of built-in types

    • Constructor of X initializes the member variables using the initialization list syntax

    • Main function demonstrates the use of "pseudo-constructors" for ordinary definitions and dynamic memory allocation

Page 176:

  • Example of composition and inheritance

    • Class A with an integer member variable and a function

    • Class B with an integer member variable and a function

    • Class C derived from class B with an embedded object of class A

    • Constructor of C calls the base class constructor and initializes the embedded object using the initialization list syntax

    • C redefines the function and calls the function of the embedded object and the base class function

    • Main function creates an object of class C

Page 177:

  • In C++, when creating an object of a derived class, an object of the base class is created first by calling its constructor.

  • Then, the specific elements of the derived class are added by calling the constructor of the derived class.

  • The declaration of the derived object must include initialization values for both the specific elements and the base class object.

  • If the base class has a default constructor or an implicitly parameterized constructor, there is no need to specify the parameters transferred to the base class object.

Page 178:

  • There are several situations regarding the copy constructor in C++ inheritance.

  • If both the derived class and the base class do not have a defined copy constructor, the compiler creates a default copy constructor that copies the members one by one.

  • If the base class has a defined copy constructor but the derived class does not, the compiler creates a default copy constructor for the derived class that calls the copy constructor of the base class.

  • If a copy constructor is defined for the derived class, it is responsible for transferring the values of the base class members.

Page 179:

  • Constructors are called in the order of defining the objects as members of the class and in the order of inheritance.

  • At each level, the constructor of the base class is called first, then the constructors of the member objects in the respective class (called in the order of definition), and finally the constructor of the derived class.

  • The next level is then processed in the order of inheritance.

  • Destructors are called in the reverse order of constructors.

Page 180:

  • The code example on this page demonstrates the order of constructor and destructor calls.

  • The constructors and destructors of the classes are defined using the CLASS macro.

  • The clss2 class has member objects of clss and cls classes.

  • The main function creates an object of the clss2 class.

Page 181:

  • The output of the code example on page 180 shows the order of constructor and destructor calls.

  • The constructors are called in the order: Base1, Member1, Member2, Derived1, Member3, Member4, Derived2.

  • The destructors are called in the reverse order: Derived2, Member4, Member3, Derived1, Member2, Member1, Base1.

Page 182:

  • The CLASS macro is defined to simplify the code example on page 180.

  • The output of the code example is shown, demonstrating the order of constructor and destructor calls.

Page 183:

  • The CLASS macro is defined again for the code example on page 184.

  • The output of the code example is shown, demonstrating the order of constructor and destructor calls.

Page 184:

  • In C++ inheritance, the derived class has access to all protected or public members of the base class.

  • It is allowed to redefine the member functions of the base class with member functions of the derived class.

  • There are two ways to redefine a member function: with the same prototype as in the base class (redefining), or by changing the argument list or return type.

Page 185:

  • An example is given to demonstrate redefining a member function while keeping the same prototype and return type.

  • The Derivata class inherits from the Baza class and redefines the afis function.

  • The main function creates an object of the Derivata class and calls the afis function.

Page 186:

  • Another example is given to demonstrate redefining a member function without keeping the same prototype and return type.

  • The Derivata class inherits from the Baza class and redefines the afis function with an additional parameter.

  • The main function creates an object of the Derivata class and calls the afis function with different arguments.

Page 187:

  • Code example of inheritance and function overriding in C++

  • Class Base with two member functions f() and g()

  • Class Derived1 derived from Base with a redefined g() function

  • Class Derived2 derived from Base with a redefined f() function

  • main() function with instances of Derived1 and Derived2 and function calls

Page 188:

  • Code example of inheritance and function overriding in C++

  • Class Base with two member functions f() and g()

  • Class Derived3 derived from Base with a redefined f() function

  • Class Derived4 derived from Base with a redefined f() function with a different argument list

  • main() function with instances of Derived3 and Derived4 and function calls

Page 189:

  • Changing the interface of a base class by modifying the return type or function signature

  • This contradicts polymorphism, which relies on preserving the base class interface

Page 190:

  • Special considerations for constructor and destructor functions in inheritance

  • They are not inherited and need to be redefined in the derived class

  • Similar to the behavior of the assignment operator

Page 191:

  • Functions that are not automatically inherited in C++

  • Example of the operator= function in classes Forma and Cerc

  • The derived class needs to explicitly call the base class operator=

Page 192:

  • Inheritance and static member functions in C++

  • Static member functions are inherited in the derived class

  • Redefining a static member function hides other overloaded versions

  • Changing the signature of a base class function hides other versions

  • Static member functions cannot be virtual

Page 193:

  • Inheritance and static member functions in C++

  • Example of classes Base and Derived with static member functions

  • The derived class can hide the base class static member function with the same name

  • The derived class can also call the base class static member function

Page 194:

  • Access modifiers in inheritance

  • public, protected, and private modifiers in inheritance

  • The access level of base class members in the derived class depends on the modifier used

Page 195:

  • Example of inheritance with access modifiers

  • Class Baza with a member function f()

  • Class Derivata derived from Baza

  • The accessibility of f() in Derivata depends on the access modifier used in inheritance

Page 196:

  • Inheritance with the private specifier

  • It is better to use composition instead of private inheritance

  • Private members of the base class are hidden in the derived class

  • Public and protected members become private in the derived class

  • Objects obtained through private inheritance are treated differently from objects of the base class

Page 197:

  • Inheritance in C++

  • Private inheritance

    • Example code with a class called "Pet" and a class called "Goldfish"

    • The "Goldfish" class inherits privately from the "Pet" class

    • The "Goldfish" class uses the "using" keyword to expose the "eat" and "sleep" functions from the "Pet" class

Page 198:

  • Protected inheritance

  • Similar to private inheritance, but with some differences

  • Good practice is to have instance variables as private and functions that modify them as protected

  • Syntax: class derived: protected base {…Î

  • All public and protected members of the base class become protected in the derived class

Page 199:

  • Public inheritance

  • Example code with a class called "Base" and two derived classes called "Derived1" and "Derived2"

  • The "Derived2" class has a function called "set" that modifies the "i" variable from the base class

Page 200:

  • Protected inheritance with public derived class

  • Example code with a class called "Base" and two derived classes called "Derived1" and "Derived2"

  • The "Derived2" class has a function called "set" that modifies the "i" variable from the base class

Page 201:

  • Private inheritance with public derived class

  • Example code with a class called "Base" and two derived classes called "Derived1" and "Derived2"

  • The "Derived2" class has a function called "set" that tries to modify the "i" variable from the base class, but it is inaccessible due to private inheritance

Page 202:

  • Multiple inheritance

  • Few languages have multiple inheritance

  • Syntax: class Derived: [access modifiers] Base1, [access modifiers] Base2, ...

  • Example code with classes "Imprimanta", "Scaner", and "Multifunctionala" that demonstrate multiple inheritance

Page 203:

  • Multiple inheritance example with potential problems

  • Example code with classes "Baza", "Derivata_1", "Derivata_2", and "Derivata_3"

  • The "Derivata_3" class inherits from both "Derivata_1" and "Derivata_2", which leads to duplicate variables from the "Baza" class

Page 204:

  • Ambiguities in multiple inheritance (diamond problem)

  • Example code with classes "base", "derived1", "derived2", and "derived3"

  • The "derived3" class inherits from both "derived1" and "derived2", causing ambiguity when accessing the "i" variable

Page 205:

  • Virtual inheritance to solve the diamond problem

  • Example code with classes "base", "derived1", "derived2", and "derived3