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:
employeewith 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:
stackwithinit(),push(), andpop()as member functionsstckandtosas member variables
Page 27:
Defining member functions outside the class:
Syntax:
return_type ClassName::function_name(parameters) { // function body }Example: defining
push()function forstackclass
Page 28:
Scope resolution operator:
::used to specify the class to which a member function belongsAllows other classes to use the same function names
Page 29:
Complete program example using the
stackclass:Includes the
iostreamlibraryDefines the
stackclass withinit(),push(), andpop()member functionsDefines the
main()function that creates twostackobjects 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
myclasswith two private variablesaandbset_abfunction sets the values ofaandbsumfunction is a friend function ofmyclassand returns the sum ofaandbmainfunction creates an object ofmyclass, sets the values ofaandb, and prints the sum ofaandb
Page 45:
Code includes two classes
C1andC2with a private variablestatusset_statusfunction sets the value ofstatusidlefunction checks if bothC1andC2objects haveIDLEstatus and returns 1 if true, 0 otherwisemainfunction creates objects ofC1andC2, sets their status toIDLE, 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
C1andC2with a private variablestatusset_statusfunction sets the value ofstatusidlefunction is a member function ofC1and checks if bothC1andC2objects haveIDLEstatus and returns 1 if true, 0 otherwisemainfunction creates objects ofC1andC2, sets their status toIDLE, 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
TwoValuesandMinTwoValuesclass has two private variablesaandbMinclass is a friend class ofTwoValuesand has a functionminthat returns the minimum value betweenaandbmainfunction creates an object ofTwoValuesand an object ofMin, 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
maxthat returns the maximum value between two integersmainfunction calls themaxfunction 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
myclasswith two private variablesaandbinitfunction initializes the values ofaandbshowfunction prints the values ofaandbmainfunction creates an object ofmyclass, initializes its values, and prints them
Page 54:
Code includes a class
myclasswith two private variablesaandbinitfunction initializes the values ofaandbshowfunction prints the values ofaandbmainfunction creates an object ofmyclass, 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
clswith a constructor and destructorClass
clsswith a constructor and destructorClass
clss2with a constructor and destructormain()function creating an object of classclss2
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
MyClassfrees 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
arrayCopy 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::memberorobject.member
Page 83:
Common use of static member functions
Example code with a class
static_typeInitialization 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
locis defined with two private member variableslongitudeandlatitude.The class has a default constructor and a parameterized constructor.
The class has a member function
show()that displays the values oflongitudeandlatitude.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 classlocand 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
locis defined with two private member variableslongitudeandlatitude.The class has a default constructor and a parameterized constructor.
The class has a member function
show()that displays the values oflongitudeandlatitude.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 classlocand performs increment and decrement operations using the overloaded++and--operators.
Page 115:
For the postfix version of
++and--, an additional parameterint xis 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 + classTypeand another forclassType + int.
Page 118:
The class
locis defined with two private member variableslongitudeandlatitude.The class has a default constructor and a parameterized constructor.
The class has a member function
show()that displays the values oflongitudeandlatitude.The class overloads the
=operator using a member function.The class overloads the
+operator forloc + intusing a friend function.The class overloads the
+operator forint + locusing a friend function.The
main()function creates three objects of classlocand 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 intoo.operator[](3).
Page 120:
The class
atypeis defined with a private member arraya.The class has a parameterized constructor.
The class overloads the
[]operator as a member function.The
main()function creates an object of classatypeand 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
atypewith an arrayaof size 3Constructor initializes the array with values
i,j, andkOverloaded
operator[]provides range checking foratypeIf index is out of range, a "Boundary Error" message is displayed and the program exits
mainfunction creates an objectobof typeatypeob[1]is displayed, which outputs the value at index 1 (2)ob[1]is assigned a new value of 25ob[3]is assigned a value of 44, which generates a runtime error
Page 124:
Overloading
operator+for classlocoperator+takes another objectop2of typelocas an argumentCreates a temporary object
tempAdds the
longitudeandlatitudevalues ofop2and the current object totempReturns
tempmainfunction creates two objectsob1andob2of typelocob1.show()displays thelongitudeandlatitudevalues ofob1ob1(7, 8)is called, which sets thelongitudeandlatitudevalues ofob1to 7 and 8 respectivelyob1.show()displays the updated values ofob1ob1 = ob2 + ob1(10, 10)addsob2and the result ofob1(10, 10)and assigns it toob1ob1.show()displays the updated values ofob1
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,throwkeywords are usedtryblock throws an exception withthrowwhich is caught bycatchAfter catching, execution in the
catchblock ends and control is passed "upwards", not returning to the point wherethrowwas called
Page 126:
Type of argument
argincatchdetermines whichcatchblock is executed if no exception is generatedcatchblocks are checked in the order they are written, the first matching type is used
Page 127:
Observations about exception handling in C++
If
throwis used and there is notryblock from which the exception was thrown or a function called from atryblock: errorIf there is no matching
catchassociated with thethrow(equal data types), the program terminates withterminate()terminate()can be redefined to do something else
Page 128:
Example of handling memory allocation error using exceptions
Class
TestTrywith a pointervand an integernConstructor tries to allocate memory using
newIf allocation fails, a "Allocation Failure" message is displayed and the program exits
mainfunction creates an objectTof typeTestTry
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_okthrows an exception with the value 10The exception is caught in a
catchblock with anintparameter and the message "Exception 10" is displayedmainfunction callsTest_Throw_okAnother example is given where the exception is not caught
Page 131:
Throwing an exception from a function
Class
TestTrywith a functionTest_Throw_FunctieTest_Throw_Functiecalls a functionTestmultiple times with different valuesIf the value is less than 0, it throws an exception with the value
The exception is caught in a
catchblock with anintparameter and the value is displayedmainfunction creates an objectTof typeTestTryand callsTest_Throw_Functie
Page 132:
Example of a local try-catch block in a function
Class
TestTrywith a functionTest_Try_LocalTest_Try_Localdeclares a variablexand assigns it different valuesCalls a function
Try_in_functiewithxas an argumentIf
xis less than 0, it throws an exception with the valueThe exception is caught in a
catchblock with anintparameter and the value is displayedmainfunction creates an objectTof typeTestTryand callsTest_Try_Local
Page 133:
Function
Exceptii_multiplein C++ handles exceptionsIf
xis less than 0, throws an integer exceptionIf
xis equal to 0, throws a character exceptionIf
xis greater than 0, throws a double exceptionIf any exception is caught, prints "Catch macar una!"
mainfunction callsExceptii_multiplewith different values ofx
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
throwkeywordThis 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 typeExample code demonstrates this behavior
Page 139:
Implementation of an exception class hierarchy starting from
std::exceptionC++98 version provides details about
<exception>and its member functions
Page 140:
Implementation of an exception class hierarchy starting from
std::exceptionExample 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
fthat handles exceptionsThe 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
Yhas an embedded object of classXThe 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
Xand a derived classYthat inherits fromX.The derived class
Yhas its own memberiand 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, andDerivata2with 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
Barand derived classMyTypewith an initialization list in the constructor.
Page 154
Example 2 of initialization list for constructors.
Shows classes
Alta_clasa,Bar, and derived classMyType2with 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
CLASSmacro.The
clss2class has member objects ofclssandclsclasses.The
mainfunction creates an object of theclss2class.
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
CLASSmacro 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
CLASSmacro 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
Derivataclass inherits from theBazaclass and redefines theafisfunction.The
mainfunction creates an object of theDerivataclass and calls theafisfunction.
Page 186:
Another example is given to demonstrate redefining a member function without keeping the same prototype and return type.
The
Derivataclass inherits from theBazaclass and redefines theafisfunction with an additional parameter.The
mainfunction creates an object of theDerivataclass and calls theafisfunction with different arguments.
Page 187:
Code example of inheritance and function overriding in C++
Class
Basewith two member functionsf()andg()Class
Derived1derived fromBasewith a redefinedg()functionClass
Derived2derived fromBasewith a redefinedf()functionmain()function with instances ofDerived1andDerived2and function calls
Page 188:
Code example of inheritance and function overriding in C++
Class
Basewith two member functionsf()andg()Class
Derived3derived fromBasewith a redefinedf()functionClass
Derived4derived fromBasewith a redefinedf()function with a different argument listmain()function with instances ofDerived3andDerived4and 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 classesFormaandCercThe 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
BaseandDerivedwith static member functionsThe 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, andprivatemodifiers in inheritanceThe access level of base class members in the derived class depends on the modifier used
Page 195:
Example of inheritance with access modifiers
Class
Bazawith a member functionf()Class
Derivataderived fromBazaThe accessibility of
f()inDerivatadepends on the access modifier used in inheritance
Page 196:
Inheritance with the
privatespecifierIt 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