COMP 345 Advanced Program Design with C 1

  • Slides: 64
Download presentation
COMP 345 - Advanced Program Design with C++ 1 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 1 Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Aggregate data types: struct class Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 2 Aggregate data types • An

COMP 345 - Advanced Program Design with C++ 2 Aggregate data types • An aggregate data type represents a type that contains other data elements. • C++ aggregate data types: array, struct and class • Array: collection of values of same type • Struct: collection of values of different types • Class: conceptually, a structure that can also “contain” functions • Treated as an aggregated entity that can be manipulated as a unit. • A struct or a class is a user-defined data type, so it must first be declared prior to declaring any variables of this new type. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 3 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 3 Click to edit Master title style struct Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 4 Structure vs. class • C++

COMP 345 - Advanced Program Design with C++ 4 Structure vs. class • C++ expanded the notion of struct from C to create classes. • For backward compatibility, the struct syntax was kept is C++. • As classes are an expanded struct, it is also possible to declare and use a struct that includes member functions, and that even inherits from another struct, just like classes. • The only difference between class and struct is that the members of a struct are public by default, but private by default for a class. • A struct that does not use object-oriented features is nicknamed a POD for “plain old data structure”. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 5 Using a POD • Once

COMP 345 - Advanced Program Design with C++ 5 Using a POD • Once the struct has been declared, it can be used as any other type • The members of a struct can be referred to using the dot notation Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 6 Using a POD Concordia University

COMP 345 - Advanced Program Design with C++ 6 Using a POD Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 7 Using a POD Concordia University

COMP 345 - Advanced Program Design with C++ 7 Using a POD Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 8 Using a POD • Structures

COMP 345 - Advanced Program Design with C++ 8 Using a POD • Structures can be initialized, assigned, passed as parameters to functions, or referred to by pointers. • Pitfall: if a structure contains a pointer variable, then its memory allocation/deallocation must be done explicitly for that member as, for example, assigning a structure to another would only copy the pointer value and not do a copy of the value pointed to by the pointer, i. e. a deep copy. • As soon as one declares any data structure that contains a pointer, great care has to be taken to ensure that the memory allocated to the object pointed to by the pointer members is managed correctly. • We will see more about that when we talk about classes. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 9 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 9 Click to edit Master title style class Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 10 Class declaration • A class

COMP 345 - Advanced Program Design with C++ 10 Class declaration • A class is an Abstract Data Type, i. e. a data type that defines both the data • • contained in the data elements it defines, as well as the behavior and/or constraints that applies to elements of this type. A C++ class represents an abstract data type by allowing functions to be syntactically encapsulated into its definition, along with its data elements. The syntax of a class definition is the same as for a struct. As opposed to Java classes, C++ allows to have class declarations that do not include the definition of the functions it encapsulates. This enables the possibility to separate the class declaration from its implementation code, which provides the implementation of the member functions of a class. • Class declaration (in the. h file): Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 11 Declaring and using objects •

COMP 345 - Advanced Program Design with C++ 11 Declaring and using objects • Variables of a class type are referred to as objects. • Objects are declared using the same syntax as for basic types. Day. Of. Year today; Day. Of. Year *birthday = new Day. Of. Year(); • Class types can be used anywhere a type can be used: • As type of a variable • As parameter to a function • As a return type to a function • As a value pointed to by a pointer • Members of a class are referred to using the dot notation and their access is regulated by the private, public and protected access specifiers. • The members of an object can be referred to using the dot notation: int day 1 = today. get. Day(); int day 2 = *birthday. get. Day(); // equivalent int day 3 = birthday->get. Day(); // equivalent Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 12 Class implementation • Use the

COMP 345 - Advanced Program Design with C++ 12 Class implementation • Use the scope resolution operator to specify to which class the member functions that you define belong to (in the. cpp file). Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 13 Header file, implementation file •

COMP 345 - Advanced Program Design with C++ 13 Header file, implementation file • Good physical design of your program dictates that you should have: • Class and member function declarations in header files (. h) • Implementation code for all member functions in a corresponding implementation file (. cpp) • The implementation file is the compilation unit, and needs to #include its corresponding header file, as it does not contain a class declaration. • If a program uses free functions, or free operators, then: • Free function and free operator headers go in the header file. • Free function and free operator implementation go in the implementation file. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 14 Kinds of methods • Member

COMP 345 - Advanced Program Design with C++ 14 Kinds of methods • Member functions can be categorized as: • Accessor: method whose goal is to expose a value in the state of an object, generally the value of a particular data member. • Mutator: method whose goal is to change a value in the state of an object. • Service method: method that exposes some service or desired behavior to other classes/objects. • Internal behavior methods: methods that are used by the class/object itself internally, that defines some of its behavior that should not be triggered explicitly from the exterior. These methods should thus be private. • Constructor: method whose goal is to manage the operations to be performed as an object is created. • Destructor: method whose goal is to manage the operations to be performed as an object is destroyed. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 15 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 15 Click to edit Master title style inline functions and methods Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 16 Inline functions/methods • A function

COMP 345 - Advanced Program Design with C++ 16 Inline functions/methods • A function (or method) can be declared as inline, meaning that its entire code is to be replacing any call to this function. • Function inlining aims at execution optimization by eliminating the function call mechanism overhead. • However, it has the disadvantage of leading to code bloat if the body of the inline function contains a large amount of code and/or is consuming a large amount of memory and is called frequently at different places in the code. • To define a function as inline, one needs to include the inline keyword as a prefix to the function definition. The function declaration does not need to have the inline prefix. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 17 Inline functions/methods • If the

COMP 345 - Advanced Program Design with C++ 17 Inline functions/methods • If the function is a method, one can provide the implementation code of the method in the class declaration, implicitly stating that the method is to be considered inline. • However, one might also declare the method in the regular fashion in the class declaration, and prefix the method definition with the inline prefix. OR Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

18 COMP 345 - Advanced Program Design with C++ Inline functions/methods • Technical explanation:

18 COMP 345 - Advanced Program Design with C++ Inline functions/methods • Technical explanation: • In order to be able to make the code substitution, the compiler needs the definition of the inline function. • Thus, inline functions' definitions must be found in all the compilation unit in which they are used. • To achieve that, we may put their definition in the header file in which they are declared, either: • In the class declaration. • As a function definition after the class declaration. • In other words, inline functions have internal linkage. If you want to make an inline function accessible to other compilation units, they must include the definition of the inline function. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 19 Inline functions/methods • Note that

COMP 345 - Advanced Program Design with C++ 19 Inline functions/methods • Note that declaring a function/method as inline is only a hint for the compiler, and that the compiler may choose not to inline a function if it is not possible, e. g. for recursive functions. • Rule of thumb: Inline your functions that have very short function definitions. Accessor methods are very good candidates for method inlining. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 20 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 20 Click to edit Master title style const specifier Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 21 The const specifier • Specifies

COMP 345 - Advanced Program Design with C++ 21 The const specifier • Specifies that its subject is constant, i. e. that its value cannot be changed after it is set. Can be applied to: • Variables: A variable may be declared as const, which signifies that its value cannot be changed after it is initialized. It assumes that the variable is initialized upon declaration. • Function parameters: Declaring a function parameter as const means that the value of this parameter cannot be changed by the execution of the function. • Methods: Declaring a method as const means that this function will not alter the state of the object to which it belongs. By extension, only methods declared as const can be called on an object that was itself declared as const upon declaration. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 22 The const specifier • Pointers

COMP 345 - Advanced Program Design with C++ 22 The const specifier • Pointers involve two different concepts • the pointer itself • the value pointed to • These two different concepts can be declared separately as const • When combined and repeated, this leads to mind-boggling concepts: Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 23 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 23 Click to edit Master title style static specifier Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 24 Static members • A member

COMP 345 - Advanced Program Design with C++ 24 Static members • A member of a class can be declared as static, which means that this member is a class member, i. e. it belongs to the class as a whole an can be called on the class rather than on the objects. • If it is a data member, its value is unique across all objects of the class, i. e. it is a “class global variable”. • If a member function is declared as static, it can only use other members that are also declared as static. • Used to define state and behavior that is independent of any particular object’s state instantiated from this class. • Static member variables are generally initialized outside of the class declaration. Only constant static integral members can be initialized inside of the class declaration. The initialized value must be a constant expression. • Other languages allow static classes (e. g. C#), which C++ does not have. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 25 Static members: use and initialization

COMP 345 - Advanced Program Design with C++ 25 Static members: use and initialization • Pitfall: There are variations of these restrictions depending on the specific version/standard of C++ you use. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 26 Static variables • Non-member variables

COMP 345 - Advanced Program Design with C++ 26 Static variables • Non-member variables can also be declared as static, which has a slightly different meaning: • When you declare a variable or function at file scope the static keyword specifies that the variable or function has internal linkage, i. e. it cannot be referred to outside of the compilation unit in which it is declared. • When you declare a local variable to a function as static, the variable has static duration, i. e. its value is kept even when the execution goes out of the scope of this function. In other words, it is a “global variable that has local scope to this function”. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 27 Static variables • All static

COMP 345 - Advanced Program Design with C++ 27 Static variables • All static variables persist from the start of the execution of the program until the program terminates. • Depending on where it is used, the static keyword has different meaning for non-member variables: • Variable d has local scope and no external linkage. • So does variable c, plus, it retains its value even when the f() function is not being executed, and is initialized only once. • Both a and b can be accessed from the point of declaration by all the code to the end of the file. But a can be used in other files because it has external linkage. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 28 Static: sum-up • To sum-up:

COMP 345 - Advanced Program Design with C++ 28 Static: sum-up • To sum-up: • A variable declared static within the body of a function maintains its value between invocations of the function. • A variable declared static within a file scope is accessible by all functions within that compilation unit. However, it is not accessible by functions from other compilation units. • Free functions declared static within a compilation unit may only be called by other functions within that compilation unit. • static class members exist as members of the class rather than as an instance in each object of the class. There is only a single instance of each static data member for the entire class. • Non-static member functions can access all data members of the class: static and non-static. • static member functions can only operate on the static data members, or call other static member functions. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 29 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 29 Click to edit Master title style friends Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 30 Friends • In principle, private

COMP 345 - Advanced Program Design with C++ 30 Friends • In principle, private and protected members of a class cannot be accessed from outside the class in which they are declared. • A friend (function or class) of a class may access the members designated as private or protected. • Friends are functions/methods or classes declared as such within a class. • Friends are not members, so they are not inherited from a superclass. • Widely criticized for being a “rogue feature”: • Makes the language more complex to implement. • Breach of the information hiding principle. • If overused, creates a proliferation of exceptions to information hiding, and thus confusion in the design. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 31 Friends (free function friend) Concordia

COMP 345 - Advanced Program Design with C++ 31 Friends (free function friend) Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 32 Friends (free function friend) Concordia

COMP 345 - Advanced Program Design with C++ 32 Friends (free function friend) Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 33 Friends (friend class) Concordia University

COMP 345 - Advanced Program Design with C++ 33 Friends (friend class) Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 34 Friends (friend class) Concordia University

COMP 345 - Advanced Program Design with C++ 34 Friends (friend class) Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 35 Friends (member function friend) Concordia

COMP 345 - Advanced Program Design with C++ 35 Friends (member function friend) Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 36 Friends (member function friend) Concordia

COMP 345 - Advanced Program Design with C++ 36 Friends (member function friend) Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 37 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 37 Click to edit Master title style Constructors and destructors Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 38 Constructors and destructors • C++

COMP 345 - Advanced Program Design with C++ 38 Constructors and destructors • C++ relies on constructors and destructors for the creation and destruction of objects. • A constructor is called any time an object is instantiated : • Using a variable declaration (allocated on the stack): Day. Of. Year birthday; • Using a pointer variable and calling the new operator (allocated on the heap): Day. Of. Year *today = new Day. Of. Year(); • During an explicit call to a constructor: birthday = Day. Of. Year(); • The destructor is called any time an object is to be destroyed: • When going out of a function scope, all variables declared in that function scope are destroyed by automatically calling their destructor before the stack frame is popped from the function call stack. • When the delete operator is explicitly called on a pointer variable. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 39 Constructors and destructors • To

COMP 345 - Advanced Program Design with C++ 39 Constructors and destructors • To sum-up, variables allocated on the stack are destroyed as we get out of the block`s scope, but objects allocated on the heap using new need to be manually destroyed using delete. • Rule of thumb: for every new, there should be a corresponding delete somewhere. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 40 Constructor declaration and implementation •

COMP 345 - Advanced Program Design with C++ 40 Constructor declaration and implementation • A constructor is a member function that has the same name as its class. • Can have as many constructors as needed. • The “default constructor” is the constructor that does not take any parameter. It is the one called when no specific constructor is mentioned during instantiation. • If you include no constructors in your class, the compiler will provide an automatically generated default constructor for basic memory allocation of data members, but not to the objects they are pointing to, if they are pointers. • If you include at least one constructor, it will not be generated, thus you may end up having no default constructor defined. • Rule of thumb: if you define your own constructor(s), make sure that you provide a default constructor, as the default constructor is likely to be called implicitly by the runtime system. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 41 Constructor declaration and implementation •

COMP 345 - Advanced Program Design with C++ 41 Constructor declaration and implementation • Constructors are differentiated by their parameter lists. • Parameters are generally used to pass values for data members initialization. • The call to the default constructor should not use parentheses, as it would make it syntactically equivalent to a function header declaration: Day. Of. Year date 3(); // function header declaration Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 42 Constructor declaration and implementation •

COMP 345 - Advanced Program Design with C++ 42 Constructor declaration and implementation • For the implementation, constructors are easily recognizable by being referred to as class. Name: : class. Name : • C++ also provides a constructor initialization list feature that allows one to declare how are the initialization mappings done between the parameters of the constructor and the data members of the class: • The preceding two examples are implementing two constructors whose effect is the same. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 43 Constructor declaration and implementation •

COMP 345 - Advanced Program Design with C++ 43 Constructor declaration and implementation • Constructors can also act as guards. • A guard verifies that certain preconditions are met before proceeding and may reject the operation if preconditions are not met. • The constructor may verify that the values passed as parameters to the constructors are valid according to the specifications of the variable they are to initialize. • If valid preconditions are not met, then the constructor may report an error or throw an exception. • Including guarding conditions in your constructors leads to more robust implementation. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 44 Constructor declaration and implementation •

COMP 345 - Advanced Program Design with C++ 44 Constructor declaration and implementation • Constructors can also be explicitly called in the initialization list of the constructors of a class that contains a data member which is an object of another class. • The initialization list is the only place where a base class constructor can be called. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 45 Constructors: call chain struct A

COMP 345 - Advanced Program Design with C++ 45 Constructors: call chain struct A { // A: : A() is implicitly-defined }; struct B : A { // B: : B() is implicitly-defined, calls A: : A() }; struct C { A a; // C: : C() is implicitly-defined, calls A: : A() }; struct G : B, C { A a; // G: : G() is implicitly-defined // calls B: : B(), C: : C(), then A: : A() // complete chain: A: : A(), B: : B(), A: : A(), C: : C(), A: : A(), G: : G() }; • If a constructor does not explicitly call the base class constructors in its initialization list, the base class default constructors are called, in the order in which the base classes are declared. • This creates a chain of base constructors calls up in the inheritance hierarchy. • After all base class constructors have been called, if a constructor does not explicitly initialize some of its data members in the initialization list, the members’ default constructors are called in the order in which the members are declared. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 46 Constructors: subtelties struct F {

COMP 345 - Advanced Program Design with C++ 46 Constructors: subtelties struct F { int& ref; // reference member: must be initialized const int c; // const member: must be initialized // F: : F() is implicitly defined as deleted because: // c and ref cannot be assigned a value using the automatically generated // default constructor. // if we explicitly declare a default constructor that does nothing, // the compiler complains that ref and c are not initialized. // F() {}; // // The only way to properly create an object of that kind is to have a constructor such as: F(int newref, int newc) : ref(newref), c(newc) { } }; • If a struct/class contains constant/reference data members, they must be initialized in an explicitly defined default constructor. • If not, the default constructor is defined as deleted (i. e. does not exist). • There are many other such subtelties. Beware! Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 47 Destructors: call chain #include <iostream>

COMP 345 - Advanced Program Design with C++ 47 Destructors: call chain #include <iostream> using namespace std; struct A { A() { cout << "A: : A()" << endl; } ~A() { cout << "A: : ~A()" << endl; } }; struct B : A { B() { cout << "B: : B()" << endl; } ~B() {cout << "B: : ~B()" << endl; } }; struct C { A a; C() { cout << "C: : C()" << endl; } ~C() {cout << "C: : ~C()" << endl; } }; struct G : B, C { A a; G() { cout << "G: : G()" << endl; } ~G() {cout << "G: : ~G()" << endl; } }; int main() { cout << "creating an A: " << endl; A cout << "creating a B: " << endl; B cout << "creating a C: " << endl; C cout << "creating a G: " << endl; G cout << "deleting all: " << endl; } a; b; c; g; creating A: : A() B: : B() creating A: : A() C: : C() creating A: : A() B: : B() A: : A() C: : C() A: : A() G: : G() deleting G: : ~G() A: : ~A() C: : ~C() A: : ~A() B: : ~B() A: : ~A() an A: a B: a C: a G: all: • Destructors are called in the exact reverse order as the constructors. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 48 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 48 Click to edit Master title style inheritance Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 49 Inheritance: basics • Inheritance is

COMP 345 - Advanced Program Design with C++ 49 Inheritance: basics • Inheritance is a mechanism by which a class can be defined as a refinement of an existing class, adding supplemental data members and/or member functions to an already existing class, or redefining an inherited member function adapted to the intended behavior of the derived class. • Most object-oriented programming languages implement an inheritance mechanism, which may be implemented with different restrictions, possibilities, and run-time mechanisms. • Inheritance allows for more flexible and extensible design possibilities by allowing the definition of generic concepts to be refined into many sub-concepts that share common traits included in the generic concepts they inherit from. • Additional mechanisms can be added to simple inheritance, such as multiple inheritance or abstract classes, which C++ implements. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 50 Inheritance: terminology • A base

COMP 345 - Advanced Program Design with C++ 50 Inheritance: terminology • A base class is a class from which other classes inherit from. • Often called a super-class, or a parent or ancestor class. • A derived class is a class that inherits from a base class. • Often called a sub-class, or a child or descendent class. • Multiple inheritance is when a derived class inherits from more than one base class. • An abstract class is a class that is meant to be derived from by containing abstract member functions that do not have a definition, assuming that they will find a concrete implementation in a derived class. Because of that, an abstract class cannot be instantiated. • Will come back to abstract classes later when we cover polymorphism. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 51 Inheritance: what is inherited? •

COMP 345 - Advanced Program Design with C++ 51 Inheritance: what is inherited? • A derived class inherits all the following members from its base class(es): • Data members • Member functions • The inheritance relationship is a transitive one, meaning that a derived class also inherits the members of all its ancestor classes. • A derived class does not inherit the following members of its base class(es): • Constructors, copy constructor • Assignment operator • Destructor • Upon use, all of these are automatically called in sequence by the run-time system, but in many cases careful explicit implementation is required. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 52 Inheritance: example Concordia University Department

COMP 345 - Advanced Program Design with C++ 52 Inheritance: example Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 53 Inheritance: overriding vs overloading •

COMP 345 - Advanced Program Design with C++ 53 Inheritance: overriding vs overloading • A derived class can explicitly add new behavior, or provide different behavior for the member functions that it inherited by overriding or overloading its inherited member functions. • Overriding is when a member function is included in a derived class, having exactly the same signature as an inherited member function. • A function`s "signature" is defined as: • Function’s name • Sequence of types in parameter list • Including order, number, and types of parameters • Signature does NOT include: • Return type • const keywords used for the function or the parameters • References specifiers (&) used for the parameters Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 54 Inheritance: overriding vs overloading •

COMP 345 - Advanced Program Design with C++ 54 Inheritance: overriding vs overloading • Overloading is when two or more functions with the same name are defined in the same scope, each having different parameter lists. • Thus, overloading applies to inherited member functions, but also applies to free functions or operators available within a certain scope. • In the previous example: • Constructors are overloaded • printcheck() function is overridden Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 55 Inheritance: constructors and destructors •

COMP 345 - Advanced Program Design with C++ 55 Inheritance: constructors and destructors • Base class constructors are NOT inherited in derived classes • The run-time system automatically calls the default constructor of the class after it transitively calls the default constructors of all its ancestor classes when and object is created. • If classes have constructors explicitly defined, they can explicitly call the appropriate base class constructor. • Explicitly calling a superclass constructor is done in the initialization list. • Note that Java’s “super()” does not make sense in C++, as we can have multiple inheritance. • Base class constructor should initialize its own member variables • They are inherited by the derived class, but the derived class constructors should not be responsible for them. The same rule applies for destructors. • So derived class constructor simply calls a base class constructor to take care of its inherited members. • This way, the inherited members are always initialized in the same manner across all classes derived by a particular base class. • As destructors cannot be overloaded, they cannot be explicitly called. They should only be called implicitly by the runtime system. • Very important part of object-oriented design, especially in C++. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 56 Inheritance: constructors and destructors •

COMP 345 - Advanced Program Design with C++ 56 Inheritance: constructors and destructors • Given the following constructors defined for the Employee class: • One can define constructors for the Hourly. Employee derived class that explicitly calls its appropriate base class constructors: • If no explicit call is made, the run-time system will call the base class` default constructor. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 57 Inheritance: assignment operator and copy

COMP 345 - Advanced Program Design with C++ 57 Inheritance: assignment operator and copy constructor • Recall: assignment operators and copy constructors are not inherited. • But can be used in derived class definitions. • When an object is assigned, the compiler implicitly uses the copy constructor to make a copy of the object, then uses the assignment operator to assign the newly copied object. • If the class is derived from a base class, these operations are called implicitly on the ancestor classes, and each is taking care of copying the values local to their particular class, similarly to constructors. • The compiler will generate default versions of the assignment operator and copy constructor, who will do a member-wise shallow copy of the object. • If defined explicitly, an explicit call to the base class assignment operator or copy constructor is similar to how derived class constructor invokes a base class constructor. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 58 Inheritance: assignment operator and copy

COMP 345 - Advanced Program Design with C++ 58 Inheritance: assignment operator and copy constructor Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 59 Inheritance: assignment operator and copy

COMP 345 - Advanced Program Design with C++ 59 Inheritance: assignment operator and copy constructor • Calls to the assignment operator and copy constructor are frequently inserted by the compiler when the code is generated, i. e. they can be implicitly called. • A call to the assignment operator is inserted in the generated code by the compiler when an assignment is made on an object that was already previously created: • The copy constructor is implicitly called by the compiler in the following cases: • When instantiating one object and initializing it with values from another object • When passing an object by value. • When an object is returned from a function by value. • When a constructor provides a type conversion that is applicable. • So even if you don’t explicitly use them in your code, the compiler will use them implicitly in the generated code, so they have to be properly defined. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 60 Inheritance: shallow vs. deep copy

COMP 345 - Advanced Program Design with C++ 60 Inheritance: shallow vs. deep copy • Explicit definition of the copy constructor and assignment operator is absolutely necessary for classes with pointer data members. • The default ones generated by the compiler do a member-wise shallow copy of the object, i. e. it copies only the values held by the data members. • If some members are pointers, only a copy of the pointer value is made, which leads the `copy` to refer to the same memory space as the original object. • Hence, they need to explicitly implement a deep copy of the object, i. e. allocate new space and copy the value pointed to by the pointer into the newly allocated space. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 61 Multiple inheritance • A derived

COMP 345 - Advanced Program Design with C++ 61 Multiple inheritance • A derived class can have more than one base class • Syntax includes all base classes separated by commas: class derived. Multi : public base 1, base 2 {…} • Possibility for ambiguity: what if base 1 and base 2 have members with the same name? • Some believe it should never be used. • Any design that uses multiple inheritance has an equivalent one that does not use multiple inheritance. • Powerful concept that leads to even more possibilities for reusability. • Similar/different vs. Java’s interfaces. • Diamond problem: two inherited classes inherit from a common class. Solved using virtual inheritance. More on that when we discuss abstract classes later. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 62 Multiple inheritance: examples Concordia University

COMP 345 - Advanced Program Design with C++ 62 Multiple inheritance: examples Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 63 Design principles enabled by classes

COMP 345 - Advanced Program Design with C++ 63 Design principles enabled by classes as implemented by C++ • Abstraction • Details of how data is manipulated within a class or function is not known or accessible to client classes. Only what is necessary to know is available externally. • Information Hiding • Some details of how an entity is internally representing or acting are hidden to the client class. Abstraction is enforced through information hiding. • Encapsulation • Bring together data and operations in a same entity, possibly hiding some. • Classes encapsulate multiple data elements together with their behavior to form a cohesive whole representing the data and behavior of a real-world concept or entity. • Modularity • Classes enable extensible modularity by defining concepts that encapsulate both data and behavior in a self-contained unit. • Classes can be extended into more refined concepts by defining sub-classes, still maintaining modularity of the original class. • In C++, several classes/free functions can be grouped together in a single compilation unit, giving more possibilities for modularity. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020

COMP 345 - Advanced Program Design with C++ 64 References • Y. Daniel Liang,

COMP 345 - Advanced Program Design with C++ 64 References • Y. Daniel Liang, Introduction to Programming with C++ (Chapter 6, 9, 10, 14), • • Peason, 2014. Bjarne Stroustrup, The C++ Programming Language (Chapter 8, 12, 15, 16, 17, 18, 19), Addison-Wesley, 2013. Learn. Cpp. com. Shallow vs. deep copying. Learn. Cpp. com. The copy constructor and overloading the assignment operator. David Anderson. The clockwise/spiral rule. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2020