Kurt Nørmark
Department of Computer Science, Aalborg University
Abstract Previous lecture Next lecture Index References Contents | In this lecture we discuss the fundamental abstraction mechanisms in C++: classes and structs. We first concentrate on constructors and destructors. Next we look at the RAII (Resource acquisition is initialization) idea in C++, including a discussion of some of the C++11 smart pointers. We also study how to program the meaning of object copying - in copy constructors and copy assignment. Visibility and access, in particular friends, is also covered. Finally we go into operator overloading for user defined types. |
Classes, structs and namespaces Slide Contents Index References | Intern kommentar til forelæsningen om denne slide: Jeg viser en struct og et namespace i programmet. På sliden involverer jeg også namespaces, for at sætte klasser/structs på plads ift. namespaces. Brug gerne link tilbage til slide om namespaces. Måske skal jeg ikke bruge tid på de tre programmer - de var ude i F14. |
|
|
|
|
|
Class basics Slide Contents Index References |
|
Program: Class Point in C#. |
|
Program: Class Point i C++ together with a main function - member functions defined in class definition. |
|
Program: The class design of class Point. |
|
Program: Member function definitions for class Point. |
|
Program: Class Point - with in-class initializations. |
|
Program: Definition of function members. |
|
|
Functions and variables outside classes Slide Contents Index References |
|
|
|
|
|
Constructors Slide Contents Index References | Intern kommentar til forelæsningen om denne slide: Læg vægt på den specielle initialiseringssyntax. Det ville være mere primitivt og unødvendigt komplekst hvis assignment var brugt i kroppen. Munder ud i en opgave om methoder i Point og Rectangle. Tilgang til hjørnepunkterne i et rectangel, og muligheden for evt. at flytte rektanglet ved at flytte dets hjørnepunkter. Kræver god brug af references - lidt tricket faktisk. |
|
|
|
Program: A class with member initializers. |
|
|
|
Constructors - examples Slide Contents Index References |
|
Program: The Point class. |
|
Program: Implementation of the Point class constructors. |
|
Program: The Rectangle class. |
|
Program: Implementation of the Rectangle class constructors. |
|
Program: Rectangle constructors - with default initialization and subsequent assignments - BAD STYLE. |
|
Program: Sample Point and Rectangle constructions. |
|
More about constructors Slide Contents Index References |
|
|
|
|
|
|
Examples of explicit, deleted, and defaulted constructors Slide Contents Index References |
|
Program: The Point class - with explicit and deleted constructors. |
|
Program: Implementation of the Point class constructors. |
|
Program: Attempting Point constructions. |
|
Program: The Point class - with explicit and defaulted constructors. |
|
Program: Implementation of the Point class constructors. |
|
Program: Point constructions - now OK. |
|
Use of constructors Slide Contents Index References | Intern kommentar til forelæsningen om denne slide: Spørg de studerende om output af klientprogrammet - reveal på slide. Hold musen nede og kør frem... |
|
|
Program: Class Point with a variety of constructors. |
|
Program: Funny implementations of the constructors. |
|
Program: Use of constructors - with local variables of class type. |
|
Program: Actual program output. |
|
Program: An additional Point construction attempt - a trap. |
|
Program: An additional Point construction attempt - with use of uniform default initialization. |
|
Exercise 4.2. Use of constructors with object on the free store | Rewrite the program shown above such that all Point objects are constructed in the free store (on the heap). The dynamically allocated points should have the same (x,y) coordinates as the points in the program shown above. This involves use of pointer and dynamic allocation, instead of automatic variables of class type and 'static allocation'. The version of the program produced in this exercise is - in some respect - similar to a Java or C# version of the program. Discuss! Consider how to initialize the array ap, which in this version of the program should be an array of Point pointers. |
Move Constructors - C++11 Slide Contents Index References |
|
|
|
|
Use of move constructors Slide Contents Index References |
|
Program: Class Point with a variety of constructors - including a move constructor. |
|
Program: Funny implementations of the constructors. |
|
Program: Use of constructors - with local variables of class type. |
|
Program: Same program with more comments. |
|
Program: Program output. |
|
Exercise 4.3. Move constructors and copy constructors | Take a look at this variant of class Point from above - all parts in one file. Notice the difference between the parameters of the function pf above, and pf in the following version of the program. #include <cmath> #include <iostream> using namespace std; class Point { private: double x, y; public: Point(); // default constructor: (0,7) Point(double x); // (x, 20) Point(double x, double y); // (y, y) Point(const Point& p); // copy constructor: (p.x+1, p.y+2) Point(Point&& p); // move constructor: (p.x-3, p.y-4) double getx () const; double gety () const; }; std::ostream& operator<<(std::ostream&, const Point&); Point::Point(): x(0.0), y(7.0){ } Point::Point(double x_coord): x(x_coord), y(20.0){ } Point::Point(double x_coord, double y_coord): x(x_coord), y(y_coord){ } Point::Point(const Point& p): x(p.x + 1.0), y(p.y + 2.0){ } Point::Point(Point&& p): x(p.x - 3.0), y(p.y - 4.0){ } double Point::getx () const{ return x; } double Point::gety () const{ return y; } std::ostream& operator<<(std::ostream& s, const Point& p){ return s << "(" << p.getx() << "," << p.gety() << ")" ; } const Point& pf(const Point& p){ cout << "Inside pf: Parameter: " << p << endl; return p; } int f(){ Point p; cout << "Point p: " << p << endl; Point q = pf(p); cout << "Point q: " << q << endl; Point r = pf(Point{10,12}); cout << "Point r: " << r << endl; } int main(){ f(); } Predict the results of the program. More specifically, which constructors are used in f? Do you find it easy and natural to decide which kind of constructors are used for parameter passing and value return? |
Destructors Slide Contents Index References | Intern kommentar til forelæsningen om denne slide: Programmerne på denne side har en sladrehank destructor. Det går kun ud på at forstå hvornår en destructor bliver kaldt. Endvidere gør vi pointen at en pointer til et objekt ikke destrueres. VIGTIG. Går igen på næste slide... |
|
|
|
|
Program: Class Point with a destructor. |
|
Program: Implementation of the destructor that reveal its activation. |
|
Program: Illustration of destructor activation when automatic variables go out of scope . |
|
Program: Actual program output. |
|
A class that needs a destructor Slide Contents Index References | Intern kommentar til forelæsningen om denne slide: Vi arbejder nu med Points med dynamisk allokeret repræsentation (en poiner til noget). Første programgruppe illustrerer leak. Destructor klades for statisk allokerede variable, men den udfører ikke sit arbejde. VIGTIG POINTE: DESTRUCTOR KALDES IKKE PÅ POINTER (TIL EN POINT) - s i eksemplet. Næste programgruppe illustrerer en bedre destructor - som deallokerer ressourcen. PLUS KALD AF DELETE PÅ s. Opgaven introducerer en forkert copy constructor, som introducerer shared point representation. Med dette flyttes kopien når originalen flyttes (og omvendt) - pga. shared representation. Endvidere vil destructoren ikke virke, fordi den dynamisk alokerede repræsentation deletes to gange. |
|
Program: Class Point - representated as a dynamically allocated array of two doubles . |
|
Program: Implementation of class point - with an insufficient destructor . |
|
Program: A sample program with memory leaks. |
|
Program: Class Point - with a pointer representation - same as before. |
Program: Implementation of class point - now with a destructor that deallocates the Point representation. |
|
Program: A sample program - now without memory leaks. |
|
Program: Output from the program. |
|
Exercise 4.4. Point destruction - now with a problematic point copy constructor | We continue our work with class Point, using a dynamically allocated point representation. It may be beneficial to review the two version of the classes (together with client programs) on the accompanying slide. In the version below we add a copy constructor to class Point. This constructor turns out to be problematic. // Redoing the example - same header file as the previous version. class Point { private: double *point_representation; public: Point(); Point(double, double); Point(const Point&); // A new copy constructor ~Point(); // Destructor double getx () const; double gety () const; void move(double dx, double dy); }; std::ostream& operator<<(std::ostream&, const Point&); The class is implemented as follows: #include <cmath> #include <iostream> #include "point.h" Point::Point() : point_representation{new double[2]{0.0, 0.0}} { } Point::Point(double x_coord, double y_coord) : point_representation{new double[2]{x_coord, y_coord}}{ } Point::Point(const Point& p): point_representation(p.point_representation){ // ATTEMPTING copy construction. } Point::~Point(){ std::cout << "Deleting point" << "(" << getx() << "," << gety() << ")" << std::endl; delete[] point_representation; } double Point::getx () const{ return point_representation[0]; } double Point::gety () const{ return point_representation[1]; } void Point::move(double dx, double dy){ point_representation[0] += dx; point_representation[1] += dy; } std::ostream& operator<<(std::ostream& s, const Point& p){ return s << "(" << p.getx() << "," << p.gety() << ")" ; } There are problems in the following program: (1) When point r is moved (using the move member function) s is also moved. This is not as intended. In addition, the program aborts on exit from the function f. #include <iostream> #include "point.h" using namespace std; int f(){ Point p, q, r(11.0, 12.0); cout << "Point p: " << p << endl; // (0,0) cout << "Point q: " << q << endl; // (0,0) cout << "Point r: " << r << endl; // (11,12) Point s(r); // s is intended to be a copy of r. cout << "Point s: " << s << endl << endl; // (11,12) r.move(1.0, 2.0); // Moves r. cout << "Point s: " << s << endl; // (12,14) !! s is ALSO MOVED - why? cout << "Point r: " << r << endl << endl; // (12,14) // PROGRAM ABORTS ON EXIT FROM F - why? } int main(){ f(); } Explain both of the problems, and make a correct version of class Point. |
|
Resource acquisition is initialization - RAII Slide Contents Index References |
|
|
|
Program: A class Resource and its application in the function use_resource - principles only. |
|
Program: A class Resource and its application in the function use_resource - compilable version. |
|
Program: Program output - normal run. |
|
Program: Program output - with problem_condition. |
|
Smart pointers in C++11: unique_ptr and shared_ptr Slide Contents Index References |
|
|
|
|
|
Example use of unique_ptr and shared_ptr Slide Contents Index References |
|
Program: The usual class Point - nothing of particular interest. |
|
Program: The usual implementation of class Point - nothing of particular interest. |
|
Program: An illustration of raw pointers. |
|
Program: Program output. |
|
Program: An illustration of unique_ptr<Point> - same example as for raw pointers. |
|
Program: Program output. |
|
Exercise 4.6. A variant of the unique_ptr program | The program above passes a raw pointer to a Point to the function f. It is a much better idea to wrap p (the point (1,2)) in a unique_ptr already in main, and to pass a unique_ptr to f. Provide for this change. In addition we want to return (the ownership of) the unique_ptr in a2 back to main via a value return. Please do that. In this exercise, please be aware that unique pointers cannot be copied - they must be moved. |
Program: An illustration of shared_ptr<Point> - same example as for unique_ptr<Point>. |
|
Program: Program output. |
|
Exercise 4.6. A variant of the shared_ptr program | Do a similar exercise for shared_ptr, as we did for unique_ptr above (see here). The starting point is this program . More specifically, from main pass a shared pointer to f. Do NOT return the pointer from f. f should be void. Does the shared pointer survive when we return from f? What is the output in the last line of main? |
Program: Another simple illustration of shared_ptr<Point>. |
|
Program: Program output. |
|
Program: Similar program with raw pointers. |
|
Program: Program output. |
|
Other examples of unique_ptr Slide Contents Index References |
|
Program: The usual class Point - nothing of particular interest. |
|
Program: The usual implementation of class Point - nothing of particular interest. |
|
Program: Unique_ptr versus raw pointer. |
|
Program: Passing unique_ptr as parameter to a function. |
|
About use of smart pointers in C++11 Slide Contents Index References |
|
|
Copying Point objects in parameter passing Slide Contents Index References | Intern kommentar til forelæsningen om denne slide: Klient programmet viser 3 funktioner g, h og i som overfører og tilbagefører punkter pr. value og reference i forskellige kombinationer. Værdioverførsel og værdireturn kalder copy constructor. Der benyttes funny constructors - så vi kan spore deres kald. |
|
Program: Class Point with a variety of constructors. |
|
Program: Funny implementations of constructors. |
|
Program: Passing Point objects in and out of functions. |
|
Program: Actual program output. |
|
Example of copying objects: Default copying Slide Contents Index References | Intern kommentar til forelæsningen om denne slide: I de viste programmer etableres der en situation hvor 3 linesegments deler et point array. Alle tre segmenter forsøger altså at deallokere det samme array (via pointere). Fejl anden gang. |
|
|
Program: Class LineSegment WITHOUT copy constructor and and WITHOUT assignment operator. Header file. |
|
Program: The corresponding cc file - not particularly relevant. |
|
Program: A function that constructs, initializes and assigns LineSegments. |
|
Program: Program execution. |
|
|
Example of copying objects: Programmed copying Slide Contents Index References | Intern kommentar til forelæsningen om denne slide: Vi programmerer copy constructor og assignment operator for LineSegments. Disse håndterer det underliggende dynamisk allokerede lager. Kopierer når det er nødvendigt. Programmet afslører sin opførsel på std output. |
|
|
Program: Class LineSegment WITH a copy constructor and and WITH an assignment operator. Header file. |
|
Program: The corresponding cc file with implementations of the copy constructor and the assignment operator. |
|
Program: A function that constructs, initializes and assigns LineSegments. |
|
Program: Program execution. |
|
|
|
Preventing object copying Slide Contents Index References |
|
|
|
|
|
Classes and Conversion Slide Contents Index References |
Item 5 of More Effective C++ is informative about implicit type conversions |
|
|
Program: istream conversion to bool. |
|
Implicit Conversion Slide Contents Index References |
|
|
Classes and Conversion: Examples Slide Contents Index References | Intern kommentar til forelæsningen om denne slide: Hold ørerne stive i dette eksempel. Første sæt er ganske medgørlig: Point til/fra double. Næste sæt involverer triple, og konverteringer til/fra point. Konvertering af tripple til point til double til point er mystisk - og overraskende. |
|
Program: Class Point with conversion constructor and conversion operator, from and to double. |
|
Program: Class Point implementation. |
|
Program: Use implicit of the conversions. |
|
Program: Program output. |
|
|
Program: Class Tripple with Tripple(Point) constructor and a Point conversion operator. |
|
Program: Class Tripple implementation. |
|
Program: Illustration of conversions. |
|
Program: Program output. |
|
Exercise 4.7. Conversion via constructors | In the program shown on the slide above, a Point can be converted to a Tripple via a constructor Tripple(Point). The other way around, we convert a Tripple to a Point with use of a conversion operator in class Tripple In this exercise we want to provide for a more symmetric solution. We keep the constructor Tripple(Point). Your task is to program the symmetric constructor Point(Tripple). Your starting point is the header file and the cpp file You may enconter a couple of minor challenges when you rewrite the program. First, class Tripple must now be declared (it must be known by the compiler) in order to compile class Point. The reason is that class Point now uses the name Tripple (in the new constructor). As another challenge, the new constructor Point(Tripple) in class Point needs access to the three encapsulated, private data members in class Tripple. Consider setting up appropriate friendship, or program accessor member functions. With this in place, rerun the program from above. Do you get the expected results (without surprises)? On closer inspection, it seems wrong to copy a Point into a Tripple constructor, and the other way around. Program a variant where the relevant Point and Tripple constructors pass 'the other object' by const reference. Explain the changes you observe. |
Static class members Slide Contents Index References |
|
|
|
Program: A variant of class Point with static members. |
|
Program: Implementation of class Point. |
|
Program: A client of class Point. |
|
Program: Program output. |
|
|
|
Program: A variant of class Point with static member function for the defaultPoint. |
|
Program: Implementation of class Point. |
|
Program: A client of class Point. |
|
Const member functions Slide Contents Index References |
|
|
|
|
Program: A variant of Point with cached polar representation. |
|
Program: The implementation of class Point - with compilation problems. |
|
|
Const member functions - const and mutable Slide Contents Index References |
|
|
|
Program: A variant of Point with cached polar representation. |
|
Program: The implementation of class Point - with compilation problems. |
|
Program: A simple client program of Point. |
|
Program: Program output. |
|
Object Self-reference Slide Contents Index References |
|
|
|
Program: Class Point - almost the usual header file. |
|
Program: Class Point - a variant with explicit use of this. |
|
Program: A sample use of points, with emphasis on moving. |
|
|
Inline member functions Slide Contents Index References |
|
|
|
|
Concrete classes Slide Contents Index References |
|
|
|
The concept concrete class: In a concrete class the representation is part of the class definition | ||
The concept non-concrete class: In contrast, a non-concrete class can provides an interfaces to a variety of different representations |
|
|
Visibility and Access Control Slide Contents Index References |
|
|
|
|
Friends Slide Contents Index References |
|
|
|
|
|
Friends - Example 1 Slide Contents Index References |
|
Program: A function f get access to the private state of both class A and B. |
|
|
Friends - Example 2 Slide Contents Index References |
|
Program: Class A provides friendship to class B. |
|
Program: Class A and B are mutual friends of each other - problems in this version. |
|
Program: Class A and B are mutual friends of each other - this version is OK. |
|
Program: A variant were we want ma to be a friend of B and mb to be friend of A - problems in this version. |
|
Friends - class Point - notational convenience Slide Contents Index References |
|
Program: Class Point - header file. |
|
Program: Class Point - implementation - not important for this example. |
|
Program: The program including implementation of friend moving functions. |
|
|
Friends - Class Point - operator friends Slide Contents Index References |
|
|
Program: Class Point - header file. |
|
Program: Class Point - implementation - including the implementation of operator<<. |
|
Program: The program that uses the operator - nothing new here. |
|
Friends - Class Point - implicit conversion Slide Contents Index References |
|
|
|
Program: Class Point - header file. |
|
Program: Class Point - implementation - including the implementation of operator<<. |
|
Program: The program that use the operator. |
|
Discussion - Encapsulation, Visibility and Access Slide Contents Index References |
|
|
|
Exercise 4.8. Discuss encapsulation, visibility and access | Discusss encapsulation, visibility and access, based on the enclosing slide. |
Operator overloading Slide Contents Index References |
|
|
|
|
|
|
|
Example: Operator overloading in class Point Slide Contents Index References |
|
Program: Class Point with operators as members. |
|
Program: Definition of Point member functions. |
|
Program: A program that illustrates uses the Point operators. |
|
Program: Program output. |
|
Program: Class Point with non-member operators. |
|
Program: Definition of Point member functions and non-member operators. |
|
Program: An identical program that illustrates uses the Point operators. |
|
Program: Program output. |
|
Collected references Contents Index |
|
Chapter 4: Abstraction Mechanisms, Part 1
Course home Author home About producing this web Previous lecture (top) Next lecture (top) Previous lecture (bund) Next lecture (bund)
Generated: August 1, 2017, 13:28:38