Friendship in Service of Testing

Size: px
Start display at page:

Download "Friendship in Service of Testing"

Transcription

1 Friendship in Service of Testing Gábor Márton, Zoltán Porkoláb, 1 / 47

2 Agenda Introduction, principals Case study Making the example better Vision 2 / 47

3 Functional Programming Immutability Thread safe Easy to test! std::size_t fibonacci(std::size_t); ASSERT(fibonacci(0u) == 0u); ASSERT(fibonacci(1u) == 1u); ASSERT(fibonacci(2u) == 1u); ASSERT(fibonacci(3u) == 2u);... ASSERT(fibonacci(7u) == 13u); ASSERT(fibonacci(8u) == 21u); 3 / 47

4 OOP States Dependencies (e.g Strategy pattern) Bad patterns -> Side Effects (singleton) 4 / 47

5 OOP - SOLID Loosely coupled system Interface (ptr or ref) 5 / 47

6 Often very heavy, e.g. requires network dependency Inter-face dependency Inter-face Real UUT/SUT Test Double Fake Stub Mock Dependency Replacement - DR 6 / 47

7 Creational Patterns Factory Method Abstract Factory Service Locator Dependency Injection (DI) Extra Constructor / Setter DI!= Dependency Replacement 7 / 47

8 Creational Patterns Factory Method Abstract Factory Service Locator Who owns the object? Can we access the object from the test? Dependency Injection (DI) Extra Constructor / Setter DI!= Dependency Replacement 7 / 47

9 OOP - Testing Replace the dependency Access the dependency (private) To exercise them Make assertions on them 8 / 47

10 Often very heavy, e.g. requires network dependency dependency Real UUT/SUT 9 / 47

11 Often very heavy, e.g. requires network dependency dependency Real UUT/SUT No explicit interface (runtime or ct) What are the options for testing in C++? 9 / 47

12 10 / 47

13 Linker Header only code? Templates? (extern template) Requires build system support 10 / 47

14 Linker Header only code? Templates? (extern template) Requires build system support Preprocessor Black magic 10 / 47

15 Linker Header only code? Templates? (extern template) Requires build system support Preprocessor Black magic Refactor Add that interface 10 / 47

16 Seams With a seam we can alter behaviour in our program without editing the original unit under test. Link seam Preprocessor seam Object seam Compile seam 11 / 47

17 Seams With a seam we can alter behaviour in our program without editing the original unit under test. Link seam Preprocessor seam Object seam The enabling point of a seam is the place where we can make the decision to use one behaviour or another. Compile seam 11 / 47

18 Case study class Entity { public: int process(int i) { int x = ; return x * 42; } private: void test1() { Entity e; } ASSERT(e.process(1) == 42); 12 / 47

19 Case study class Entity { public: int process(int i) { int x = ; return x * 42; } private: void test1() { Entity e; } ASSERT(e.process(1) == 42); 12 / 47 Can we make it work in a multithreaded environment?

20 class Entity { public: int process(int i) { if(m.try_lock()) { int x = ; m.unlock(); return x * 42; } else { ; return 0; } } private: std::mutex m; 13 / 47

21 class Entity { public: int process(int i) { if(m.try_lock()) { int x = ; m.unlock(); return x * 42; } else { ; return 0; } } private: How to test the new logic? std::mutex m; 13 / 47

22 struct Mutex { virtual void lock() = 0; virtual void unlock() = 0; virtual bool try_lock() = 0; struct RealMutex : Mutex { struct StubMutex : Mutex { bool try_lock_result = false; virtual bool try_lock() override { } return try_lock_result; 14 / 47

23 struct Mutex { virtual void lock() = 0; virtual void unlock() = 0; virtual bool try_lock() = 0; virtual ~Mutex() {} struct RealMutex : Mutex { struct StubMutex : Mutex { bool try_lock_result = false; virtual bool try_lock() override { } return try_lock_result; 14 / 47

24 Object Seam class Entity { public: Entity(Mutex& m) : m(m) {} int process(int i) { } private: Mutex& m; 15 / 47

25 Object Seam class Entity { public: Entity(Mutex& m) : m(m) {} int process(int i) { } private: Mutex& m; Ex. of Object Seam: Entity + Mutex Enabling point: constructor 15 / 47

26 void realworldclient() { RealMutex m; Entity e(m); // Real usage of e } void testclient() { // test setup StubMutex m; Entity e(m); } m.try_lock_result = false; ASSERT(e.process(1) == 0); m.try_lock_result = true; ASSERT(e.process(1) == 42); 16 / 47

27 class Entity { public: Entity(Mutex& m) : m(m) {} int process(int i) { } private: Mutex& m; Feels so unnatural! 17 / 47

28 class Entity { public: Entity(Mutex& m) : m(m) {} int process(int i) { } private: Mutex& m; Ownership? Feels so unnatural! 17 / 47

29 class Entity { public: Entity(Mutex& m) : m(m) {} int process(int i) { } private: Mutex& m; Ownership? Extra ctor/setter Feels so unnatural! 17 / 47

30 class Entity { public: Entity(Mutex& m) : m(m) {} int process(int i) { } private: Mutex& m; Ownership? Extra ctor/setter Extra interface Feels so unnatural! Virtual functions Cache locality? 17 / 47

31 class Entity { public: Entity(Mutex& m) : m(m) {} int process(int i) { } private: Mutex& m; Ownership? Extra ctor/setter Extra interface Feels so unnatural! Virtual functions Cache locality? Pointer semantics Cache locality? 17 / 47

32 class Entity { public: Entity(Mutex& m) : m(m) {} int process(int i) { } private: Mutex& m; Ownership? Extra ctor/setter Extra interface Virtual functions Cache locality? Pointer semantics Cache locality? Type erasure? Feels so unnatural! Can t spare the virtual calls 17 / 47

33 Ownership class Entity { public: Entity(std::unique_ptr<Mutex> m) : m(std::move(m)) {} int process(int i) { if(m >try_lock()) { } else { } } Mutex& getmutex() { return *m.get(); } private: std::unique_ptr<mutex> m; void testclient() { Entity e(std::make_unique<stubmutex>()); auto& m = e.getmutex(); // assertions } 18 / 47

34 Ownership OK As before: Extra ctor, virtuals, pointer semantics, etc Extra getter 19 / 47

35 Compile Seam template <typename Mutex> class Entity { public: int process(int i) { } // Use only from tests Mutex& getmutex() { return m; } private: Mutex m; 20 / 47

36 void realworldclient() { Entity<std::mutex> e; // Real usage of e } void testclient() { struct StubMutex{ void lock() {} void unlock() {} bool try_lock_result = false; bool try_lock() { return try_lock_result; } Entity<StubMutex> e; auto& m = e.getmutex(); // assertions } 21 / 47

37 void realworldclient() { Entity<std::mutex> e; // Real usage of e } void testclient() { struct StubMutex{ No inheritance void lock() {} No virtual functions void unlock() {} bool try_lock_result = false; bool try_lock() { return try_lock_result; } Entity<StubMutex> e; auto& m = e.getmutex(); // assertions } 21 / 47

38 Ownership Locality No Extra ctor/setter Extra Interface (compile time) Extra Getter Extra Compilation Time 22 / 47

39 Extra Compilation Time - Combine with Pimpl // detail/entity.hpp namespace detail { // as before template <typename Mutex> class Entity { } // detail 23 / 47

40 // Entity.hpp class Entity { public: Entity(); ~Entity(); int process(int i); private: struct Impl; std::unique_ptr<impl> pimpl; 24 / 47

41 // Entity.cpp #include detail/entity.hpp using RealEntity = detail::entity<std::mutex>; struct Entity::Impl : RealEntity { // delegate the consturctors using RealEntity::RealEntity; Entity::Entity() : pimpl(std::make_unique<impl>()) {} Entity::~Entity() = default; int Entity::process(int i) { return pimpl->process(i); } 25 / 47

42 // Client.cpp #include Entity.hpp void realworldclient() { Entity e; } // Real usage of e // Test.cpp #include detail/entity.hpp void testclient() { struct StubMutex { detail::entity<stubmutex> e; } // Test code as before 26 / 47

43 Compile Seam + Pimpl No extra compile time But at least two compiles if detail::entity changes Entity.cpp Test.cpp Extra complexity 27 / 47

44 class Entity { public: int process(int i) { } private: std::mutex m; template <typename Mutex> class Entity { public: Mutex& getmutex() { return m; } int process(int i) { } private: Mutex m; 28 / 47

45 class Entity { public: int process(int i) { } private: std::mutex m; Intrusive template <typename Mutex> class Entity { public: Mutex& getmutex() { return m; } int process(int i) { } private: Mutex m; 28 / 47

46 Eliminate the Extra Getter template <typename Mutex> class Entity { #ifdef TEST Mutex& getmutex() { return m; } #endif 29 / 47

47 Eliminate the Extra Getter template <typename Mutex> class Entity { #ifdef TEST Mutex& getmutex() { return m; } #endif Worse Readability Maintainability 29 / 47

48 #define private public #include "Entity.hpp" #undef private // Test code comes from here 30 / 47

49 #define private public #include "Entity.hpp" #undef private // Test code comes from here Undefined behaviour The order of allocation of non-static data members with different access control is unspecified class X { public: int x; private: int y; public: int z; x z y x y z Danger, everything included from Entity.hpp is now public 31 / 47

50 Eliminate the Extra Getter - Access via a Friend Function template <typename Mutex> class Entity { public: + friend Mutex& testfriend(entity &e); int process(int i) { } private: Mutex m; 32 / 47

51 // Test.cpp struct StubMutex { StubMutex& testfriend(entity<stubmutex>& e){ } return e.m; void testclient() { Entity<StubMutex> e; auto &m = testfriend(e); // assertions } 33 / 47

52 Eliminate the Extra Getter - Access via a Friend Class template <typename Mutex> class Entity { public: + friend struct EntityTestFriend; int process(int i) { } private: Mutex m; 34 / 47

53 // Test.cpp struct StubMutex { struct EntityTestFriend { template<typename Mutex> static auto& getmutex(entity<mutex>& e) { return e.m; } void testclient() { Entity<StubMutex> e; auto &m = EntityTestFriend::getMutex(e); // assertions } 35 / 47

54 class EntityTestFriend { template<typename Mutex> static auto& getmutex(entity<mutex>& e) { return e.m; } + friend void test_try_lock_succeeds(); + friend void test_try_lock_fails(); void test_try_lock_succeeds() { Entity<StubMutex> e; auto &m = EntityTestFriend::getMutex(e); // assertion } // 36 / 47

55 class EntityTestFriend { template<typename Mutex> static auto& getmutex(entity<mutex>& e) { return e.m; } + friend void test_try_lock_succeeds(); + friend void test_try_lock_fails(); void test_try_lock_succeeds() { Entity<StubMutex> e; auto &m = EntityTestFriend::getMutex(e); // assertion } // Attorney < > EntityTestFriend Client < > Entity 36 / 47

56 class Entity { public: int process(int i) { } private: std::mutex m; template <typename Mutex> class Entity { public: friend struct EntityTestFriend; int process(int i) { } private: Mutex m; 37 / 47

57 class Entity { public: int process(int i) { } private: std::mutex m; Intrusive template <typename Mutex> class Entity { public: friend struct EntityTestFriend; int process(int i) { } private: Mutex m; 37 / 47

58 Eliminate the Extra Getter - Non-intrusive Access template <typename Mutex> class Entity { public: int process(int i) { } private: Mutex m; 38 / 47

59 // Test.cpp struct StubMutex { ACCESS_PRIVATE_FIELD( Entity<StubMutex>, StubMutex, m) void test_try_lock_fails() { Entity<StubMutex> e; auto& m = access_private::m(e); m.try_lock_result = false; ASSERT(e.process(1) == 0); } 39 / 47

60 class A { static int i; int A::i = 42; Access a private static member 40 / 47

61 class A { static int i; int A::i = 42; Access a private static member template struct private_access<&a::i>; 40 / 47

62 class A { static int i; int A::i = 42; Access a private static member template <int* PtrValue> struct private_access { friend int* get() { return PtrValue; } template struct private_access<&a::i>; 40 / 47

63 class A { static int i; int A::i = 42; Access a private static member template <int* PtrValue> struct private_access { friend int* get() { return PtrValue; } int* get(); template struct private_access<&a::i>; 40 / 47

64 class A { static int i; int A::i = 42; Access a private static member template <int* PtrValue> struct private_access { friend int* get() { return PtrValue; } int* get(); template struct private_access<&a::i>; void usage() { int* i = get(); assert(*i == 42); } 40 / 47

65 Access a private non-static member class A { int i = 42; 41 / 47

66 Access a private non-static member class A { int i = 42; template struct private_access<&a::i>; 41 / 47

67 Access a private non-static member class A { int i = 42; using PtrType = int A::*; template<ptrtype PtrValue> struct private_access { friend PtrType get() { return PtrValue; } template struct private_access<&a::i>; 41 / 47

68 Access a private non-static member class A { int i = 42; using PtrType = int A::*; template<ptrtype PtrValue> struct private_access { friend PtrType get() { return PtrValue; } PtrType get(); template struct private_access<&a::i>; 41 / 47

69 Access a private non-static member class A { int i = 42; using PtrType = int A::*; template<ptrtype PtrValue> struct private_access { friend PtrType get() { return PtrValue; } PtrType get(); template struct private_access<&a::i>; void usage() { A a; PtrType ip = get(); int& i = a.*ip; assert(i == 42); } 41 / 47

70 Can access private member fields, functions Can t access private types Can t access private ctor/dtor Link error with in-class defined private static const 42 / 47

71 43 / 47

72 Eliminate the Extra Getter - Out-of-class Friend template <typename Mutex> class Entity { public: int process(int i) { } private: Mutex m; 44 / 47

73 Eliminate the Extra Getter - Out-of-class Friend template <typename Mutex> class Entity { public: int process(int i) { } private: Mutex m; // Test.cpp friend for(entity<stubmutex>) void testclient() { Entity<StubMutex> e; auto& m = e.m; // access the private // assertions } 44 / 47

74 Clear intentions, self describing code No cumbersome accessor patterns Can access all private (types, ctor, ) Proof-of-concept implementation in clang Encapsulation (?) A good language should prevent non-intuitive, accidental failure friend for cannot be accidental 45 / 47

75 Vision class Entity { 46 / 47

76 Vision class Entity { // Test.cpp void testclient() { using EntityUnderTest = test::replacemembertype<entity, std::mutex, StubMutex>; EntityUnderTest e; auto& m = e.get<stubmutex>(); // assertions } 46 / 47

77 Thank you! Gábor Márton Questions? 47 / 47

Unit Testing in C++ with Compiler Instrumentation and Friends

Unit Testing in C++ with Compiler Instrumentation and Friends Acta Cybernetica 23 (2017) 659 686. Unit Testing in C++ with Compiler Instrumentation and Friends Gábor Márton a and Zoltán Porkoláb b Abstract In C++, test code is often interwoven with the unit we want

More information

Compile-Time Function Call Interception to Mock Functions in C/C++

Compile-Time Function Call Interception to Mock Functions in C/C++ Compile-Time Function Call Interception to Mock Functions in C/C++ Gábor Márton, Zoltán Porkoláb Ericsson Hungary Ltd., Eötvös Loránd University, Budapest martongabesz@gmail.com, zoltan.porkolab@ericsson.com,

More information

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP OOP Object oriented programming Polymorphism Encapsulation Inheritance OOP Class concepts Classes can contain: Constants Delegates Events Fields Constructors Destructors Properties Methods Nested classes

More information

6 Architecture of C++ programs

6 Architecture of C++ programs 6 Architecture of C++ programs 1 Preview managing memory and other resources "resource acquisition is initialization" (RAII) using std::auto_ptr and other smart pointers safe construction of an object

More information

Object-Oriented Programming. Lecture 2 Dr Piotr Cybula

Object-Oriented Programming. Lecture 2 Dr Piotr Cybula Object-Oriented Programming Lecture 2 Dr Piotr Cybula Encapsulation : data protection code safety and independence better team support with the code separation without «giving

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Database Systems on Modern CPU Architectures

Database Systems on Modern CPU Architectures Database Systems on Modern CPU Architectures Introduction to Modern C++ Moritz Sichert Technische Universität München Department of Informatics Chair of Data Science and Engineering Overview Prerequisites:

More information

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things. A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators

More information

MODERN AND LUCID C++ ADVANCED

MODERN AND LUCID C++ ADVANCED Informatik MODERN AND LUCID C++ ADVANCED for Professional Programmers Prof. Peter Sommerlad Thomas Corbat Director of IFS Research Assistant Rapperswil, FS 2016 LIBRARY API/ABI DESIGN PIMPL IDIOM HOURGLASS

More information

Implementing Subprograms

Implementing Subprograms Implementing Subprograms 1 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables Nested Subprograms Blocks Implementing

More information

Value Semantics and Concept Based Polymorphism Sean Parent Principal Scientist Adobe Systems Incorporated. All Rights Reserved.

Value Semantics and Concept Based Polymorphism Sean Parent Principal Scientist Adobe Systems Incorporated. All Rights Reserved. Value Semantics and Concept Based Polymorphism Sean Parent Principal Scientist 2012 Adobe Systems Incorporated. All Rights Reserved. Outline of Talk Defining Value Semantics Polymorphic Types Demo of Photoshop

More information

C++ Coding Standards and Practices. Tim Beaudet March 23rd 2015

C++ Coding Standards and Practices. Tim Beaudet March 23rd 2015 C++ Coding Standards and Practices Tim Beaudet (timbeaudet@yahoo.com) March 23rd 2015 Table of Contents Table of contents About these standards Project Source Control Build Automation Const Correctness

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Abstract Data Types and Encapsulation Concepts ISBN 0-321-33025-0 Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract

More information

Modern and Lucid C++ Advanced for Professional Programmers. Part 12 Advanced Library Design. Department I - C Plus Plus Advanced

Modern and Lucid C++ Advanced for Professional Programmers. Part 12 Advanced Library Design. Department I - C Plus Plus Advanced Department I - C Plus Plus Advanced Modern and Lucid C++ Advanced for Professional Programmers Part 12 Advanced Library Design Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 23.02.2017 HS2017 Topics

More information

C++17 and Beyond. Mark Isaacson

C++17 and Beyond. Mark Isaacson C++17 and Beyond Mark Isaacson 1 Roadmap What s coming in C++17 and C++20 The surprising utility of std::string_view C++20 s most deliciously scary feature: operator dot Making templates more accessible

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

Macros and Preprocessor. CGS 3460, Lecture 39 Apr 17, 2006 Hen-I Yang

Macros and Preprocessor. CGS 3460, Lecture 39 Apr 17, 2006 Hen-I Yang Macros and Preprocessor CGS 3460, Lecture 39 Apr 17, 2006 Hen-I Yang Previously Operations on Linked list (Create and Insert) Agenda Linked List (More insert, lookup and delete) Preprocessor Linked List

More information

Lab 2: ADT Design & Implementation

Lab 2: ADT Design & Implementation Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted

More information

Making New Pseudo-Languages with C++

Making New Pseudo-Languages with C++ Making New Pseudo-Languages with C++ Build You a C++ For Great Good ++ A 10,000 Metre Talk by David Williams-King Agenda 1/4 Introduction 2/4 Polymorphism & Multimethods 3/4 Changing the Behaviour of C++

More information

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements B-Trees 1 B-Trees nodes with many children a type node a class for B-trees 2 manipulating a B-tree an elaborate example the insertion algorithm removing elements MCS 360 Lecture 35 Introduction to Data

More information

Abstract Data Types and Encapsulation Concepts

Abstract Data Types and Encapsulation Concepts Abstract Data Types and Encapsulation Concepts The Concept of Abstraction An abstraction is a view or representation of an entity that includes only the most significant attributes The concept of abstraction

More information

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 9 G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And

More information

Index. Symbols. bit sequence, 27 ^ (exclusive OR) operator, 30 hexadecimal number, 27 left shift (<<) operator, 31 right shift (>>) operator, 32

Index. Symbols. bit sequence, 27 ^ (exclusive OR) operator, 30 hexadecimal number, 27 left shift (<<) operator, 31 right shift (>>) operator, 32 Symbols && operator, 32 operator, 32 A AddDynamicOption method, 188 AddItem method, 192 Addition operator, 18 Allocating memory, 228 overloaded delete function, 233 overloaded new function, 232 unnamed

More information

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

C++ Programming Lecture 6 Software Engineering Group

C++ Programming Lecture 6 Software Engineering Group C++ Programming Lecture 6 Software Engineering Group Philipp D. Schubert Dynamic memory allocation Quick reminder: Do not confuse between the (de)allocation operators! void* operator new ( std::size_t

More information

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd. C++11: 10 Features You Should be Using Gordon Brown @AerialMantis R&D Runtime Engineer Codeplay Software Ltd. Agenda Default and Deleted Methods Static Assertions Delegated and Inherited Constructors Null

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 10 Multithreading - Producer/Consumer Problem 2016 www.cse.unsw.edu.au/ cs6771 2. : C++11 Mutexes C++11 provides Mutex objects in the header file. General

More information

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance

More information

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING Question No: 1 ( Marks: 1 ) - Please choose one Classes like TwoDimensionalShape and ThreeDimensionalShape would normally be concrete,

More information

Chapter 12: How to Create and Use Classes

Chapter 12: How to Create and Use Classes CIS 260 C# Chapter 12: How to Create and Use Classes 1. An Introduction to Classes 1.1. How classes can be used to structure an application A class is a template to define objects with their properties

More information

Client Code - the code that uses the classes under discussion. Coupling - code in one module depends on code in another module

Client Code - the code that uses the classes under discussion. Coupling - code in one module depends on code in another module Basic Class Design Goal of OOP: Reduce complexity of software development by keeping details, and especially changes to details, from spreading throughout the entire program. Actually, the same goal as

More information

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

More information

Advanced Systems Programming

Advanced Systems Programming Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short

More information

Proposed Wording for Concurrent Data Structures: Hazard Pointer and Read Copy Update (RCU)

Proposed Wording for Concurrent Data Structures: Hazard Pointer and Read Copy Update (RCU) Document number: D0566R1 Date: 20170619 (pre Toronto) Project: Programming Language C++, WG21, SG1,SG14, LEWG, LWG Authors: Michael Wong, Maged M. Michael, Paul McKenney, Geoffrey Romer, Andrew Hunter

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Principles of Object Oriented Programming. Lecture 4

Principles of Object Oriented Programming. Lecture 4 Principles of Object Oriented Programming Lecture 4 Object-Oriented Programming There are several concepts underlying OOP: Abstract Types (Classes) Encapsulation (or Information Hiding) Polymorphism Inheritance

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

More information

Multithreading Using Lockless Lists and RCU. Ansel Sermersheim CppNow - May 2017

Multithreading Using Lockless Lists and RCU. Ansel Sermersheim CppNow - May 2017 Multithreading Using Lockless Lists and RCU Ansel Sermersheim CppNow - May 2017 1 Introduction Multithreading revisited A better way Containers + Destructors = Deadlocks Introducing a new solution: RCU

More information

A Proposal to Add a Logical Const Wrapper to the Standard Library Technical Report

A Proposal to Add a Logical Const Wrapper to the Standard Library Technical Report Doc number: N3973 Date: 2014-05-12 Project: Programming Language C++, Library Evolution Working Group Reply-to: Jonathan Coe Robert Mill A Proposal to Add a Logical

More information

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011 More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors

More information

CMSC 4023 Chapter 11

CMSC 4023 Chapter 11 11. Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language Examples Parameterized Abstract Data Types Encapsulation Constructs Naming Encapsulations

More information

A Generic Non-intrusive Smart Pointer Implementation

A Generic Non-intrusive Smart Pointer Implementation A Generic Non-intrusive Smart Pointer Implementation Anthony Williams 13th March 2001 1 Background I started writing an article about resource management using Resource Acquisition Is Initialisation (RAII),

More information

C++FA 6.1 PRACTICE FINAL EXAM

C++FA 6.1 PRACTICE FINAL EXAM C++FA 6.1 PRACTICE FINAL EXAM This practice final exam covers sections C++FA 2.1 through C++FA 4.1 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A T is a/an:

More information

Object Oriented Paradigm

Object Oriented Paradigm Object Oriented Paradigm History Simula 67 A Simulation Language 1967 (Algol 60 based) Smalltalk OO Language 1972 (1 st version) 1980 (standard) Background Ideas Record + code OBJECT (attributes + methods)

More information

ADTs & Classes. An introduction

ADTs & Classes. An introduction ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object

More information

Debug C++ Without Running. Anastasia Kazakova

Debug C++ Without Running. Anastasia Kazakova Debug C++ Without Running Anastasia Kazakova JetBrains @anastasiak2512 Agenda 1. Tricky C++ language. Show samples! 2. Seems to help but it doesn t. Why? Running / Debugging Static / dynamic code analysis

More information

Modernizing legacy C++ code

Modernizing legacy C++ code Modernizing legacy C++ code Marius Bancila mariusbancila marius.bancila Agenda Short intro Legacy and modernization Good practices Q&A Containers Resource management correctness Const correctness Type

More information

Patterns Continued and Concluded. July 26, 2017

Patterns Continued and Concluded. July 26, 2017 Patterns Continued and Concluded July 26, 2017 Review Quiz What is the purpose of the Singleton pattern? A. To advertise to other developers that the object should only be modified by `main()` B.To prevent

More information

Chapter 11. Abstract Data Types and Encapsulation Concepts 抽象数据类型 与封装结构. 孟小亮 Xiaoliang MENG, 答疑 ISBN

Chapter 11. Abstract Data Types and Encapsulation Concepts 抽象数据类型 与封装结构. 孟小亮 Xiaoliang MENG, 答疑   ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts 抽象数据类型 与封装结构 孟小亮 Xiaoliang MENG, 答疑 EMAIL: 1920525866@QQ.COM ISBN 0-321-49362-1 Chapter 11 Topics The Concept of Abstraction Introduction to Data

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Smart Pointers and Constness Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

UNIVERSITY OF SWAZILAND

UNIVERSITY OF SWAZILAND UNIVERSITY OF SWAZILAND DEPARTMENT OF COMPUTER SCIENCE CSC242 - OBJECT ORIENTED PROGRAMMING FINAL EXAMINATION MAY 2017 Instructions 1. The time allowed is THREE (3) H0URS. 2. Read all the questions in

More information

C++ Alexander Baltatzis

C++ Alexander Baltatzis C++ Alexander Baltatzis Recap Undefined behaviour int * q1 = new int[2]; delete q1; int * q2 = new int; delete [] q2; Contract with the compiler constructor How would you implement delete [] Classes with

More information

Mixin and CRTP in C++98/11. Zoltán Porkoláb, PhD.

Mixin and CRTP in C++98/11. Zoltán Porkoláb, PhD. Mixin and CRTP in C++98/11 Zoltán Porkoláb, PhD. gsd@elte.hu http://gsd.web.elte.hu C++ specific patterns Mixin Liskov substitutional principle C++11 mixins Curiously Recurring Template Pattern (CRTP)

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

SFU CMPT Topic: Classes

SFU CMPT Topic: Classes SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables

More information

ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns

ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/60 ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns Professor Jia Wang Department of Electrical

More information

Arizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373

Arizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373 Arizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373 Overview Object Creation Control Distribution Possibilities Impact of design decisions on IP control 2 Good

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 9 Multithreading (continued) 2016 www.cse.unsw.edu.au/ cs6771 2. So Far Program Workflows: Sequential, Parallel, Embarrassingly Parallel Memory: Shared Memory,

More information

Type Erasure. Nevin :-) Liber Friday, October 29, Chicago C/C++ Users Group Nevin J. Liber All Rights Reserved.

Type Erasure. Nevin :-) Liber Friday, October 29, Chicago C/C++ Users Group Nevin J. Liber All Rights Reserved. Type Erasure Nevin :-) Liber nevin@eviloverlord.com 2010 Nevin J. Liber All Rights Reserved. Chicago C/C++ Users Group 1 Type Erasure Type Erasure Pattern boost::any boost::function expression templates

More information

A Proposal to Add a Const-Propagating Wrapper to the Standard Library

A Proposal to Add a Const-Propagating Wrapper to the Standard Library Doc number: N4057 Revises: N3973 Date: 2014-07-02 Project: Programming Language C++, Library Evolution Working Group Reply-to: Jonathan Coe Robert Mill A Proposal

More information

Singleton, Factory Method, Abstract Factory, Named Constructor. Using one or more base classes to hide details from the client

Singleton, Factory Method, Abstract Factory, Named Constructor. Using one or more base classes to hide details from the client Idioms & Design Patterns Creational Introduction to Design Patterns Patterns and idioms can be grouped roughly into: Creational Patterns and idioms Singleton, Factory Method, Abstract Factory, Named Constructor

More information

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts ISBN 0-321-49362-1 Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

CS11 Introduction to C++ Fall Lecture 7

CS11 Introduction to C++ Fall Lecture 7 CS11 Introduction to C++ Fall 2012-2013 Lecture 7 Computer Strategy Game n Want to write a turn-based strategy game for the computer n Need different kinds of units for the game Different capabilities,

More information

Introduction to C++11 and its use inside Qt

Introduction to C++11 and its use inside Qt Introduction to C++11 and its use inside Qt Olivier Goffart February 2013 1/43 Introduction to C++11 and its use inside Qt About Me http://woboq.com http://code.woboq.org 2/43 Introduction to C++11 and

More information

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

the gamedesigninitiative at cornell university Lecture 7 C++ Overview Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on

More information

Patterns and Practices for Embedded TDD in C and C++ How we introduced TDD into our company

Patterns and Practices for Embedded TDD in C and C++ How we introduced TDD into our company Patterns and Practices for Embedded TDD in C and C++ How we introduced TDD into our company Work for Cornwall, England. based in Provide an embedded software development service. Introduced Lean/Agile

More information

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a. Intro to OOP - Object and class - The sequence to define and use a class in a program - How/when to use scope resolution operator - How/when to the dot operator - Should be able to write the prototype

More information

Patterns CHAPTER. Creational Patterns

Patterns CHAPTER. Creational Patterns CHAPTER Patterns 3 The previous chapter discussed the qualities that differentiate a good API from a bad API. The next couple of chapters focus on the techniques and principles of building high-quality

More information

CS304 Object Oriented Programming

CS304 Object Oriented Programming 1 CS304 Object Oriented Programming 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes?

More information

CSC 210, Exam Two Section February 1999

CSC 210, Exam Two Section February 1999 Problem Possible Score 1 12 2 16 3 18 4 14 5 20 6 20 Total 100 CSC 210, Exam Two Section 004 7 February 1999 Name Unity/Eos ID (a) The exam contains 5 pages and 6 problems. Make sure your exam is complete.

More information

Advanced C++ Topics. Alexander Warg, 2017

Advanced C++ Topics. Alexander Warg, 2017 www.kernkonzept.com Advanced C++ Topics Alexander Warg, 2017 M I C R O K E R N E L M A D E I N G E R M A N Y Overview WHAT IS BEHIND C++ Language Magics Object Life Time Object Memory Layout INTRODUCTION

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

Ch02. True/False Indicate whether the statement is true or false.

Ch02. True/False Indicate whether the statement is true or false. Ch02 True/False Indicate whether the statement is true or false. 1. The base class inherits all its properties from the derived class. 2. Inheritance is an is-a relationship. 3. In single inheritance,

More information

C++ & Object Oriented Programming Concepts The procedural programming is the standard approach used in many traditional computer languages such as BASIC, C, FORTRAN and PASCAL. The procedural programming

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010.

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010. 1 2 3 MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010 1 2 3 efficient updates with lists At http://www.sgi.com/tech/stl/ is the Standard Template Library Programmer

More information

Time : 3 hours. Full Marks : 75. Own words as far as practicable. The questions are of equal value. Answer any five questions.

Time : 3 hours. Full Marks : 75. Own words as far as practicable. The questions are of equal value. Answer any five questions. XEV (H-3) BCA (6) 2 0 1 0 Time : 3 hours Full Marks : 75 Candidates are required to give their answers in their Own words as far as practicable. The questions are of equal value. Answer any five questions.

More information

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above P.G.TRB - COMPUTER SCIENCE Total Marks : 50 Time : 30 Minutes 1. C was primarily developed as a a)systems programming language b) general purpose language c) data processing language d) none of the above

More information

Move semantics. Zoltán Porkoláb: C++11/14 1

Move semantics. Zoltán Porkoláb: C++11/14 1 Move semantics Pointers and arrays References Value vs move semantics Right value references Move semantics in C++11 Perfect forwarding Traps and pitfalls Zoltán Porkoláb: C++11/14 1 Arrays An array is

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

Structuur van Computerprogramma s 2

Structuur van Computerprogramma s 2 Structuur van Computerprogramma s 2 dr. Dirk Deridder Dirk.Deridder@vub.ac.be http://soft.vub.ac.be/ Vrije Universiteit Brussel - Faculty of Science and Bio-Engineering Sciences - Computer Science Department

More information

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

Operator overloading. Conversions. friend. inline

Operator overloading. Conversions. friend. inline Operator overloading Conversions friend inline. Operator Overloading Operators like +, -, *, are actually methods, and can be overloaded. Syntactic sugar. What is it good for - 1 Natural usage. compare:

More information

26.1 Introduction Programming Preliminaries... 2

26.1 Introduction Programming Preliminaries... 2 Department of Computer Science Tackling Design Patterns Chapter 27: Proxy Design Pattern Copyright c 2016 by Linda Marshall and Vreda Pieterse. All rights reserved. Contents 26.1 Introduction.................................

More information

DYNAMIC MEMORY ALLOCATION ON REAL-TIME LINUX

DYNAMIC MEMORY ALLOCATION ON REAL-TIME LINUX DYNAMIC MEMORY ALLOCATION ON REAL-TIME LINUX Jianping Shen Institut Dr. Foerster GmbH und Co. KG In Laisen 70, 72766, Reutlingen, Germany shen.jianping@foerstergroup.de Michael Hamal Institut Dr. Foerster

More information

I m sure you have been annoyed at least once by having to type out types like this:

I m sure you have been annoyed at least once by having to type out types like this: Type Inference The first thing I m going to talk about is type inference. C++11 provides mechanisms which make the compiler deduce the types of expressions. These features allow you to make your code more

More information

Increases Program Structure which results in greater reliability. Polymorphism

Increases Program Structure which results in greater reliability. Polymorphism UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the

More information

Test, Code, Design: Inverting the Waterfall

Test, Code, Design: Inverting the Waterfall Test, Code, Design: Inverting the Waterfall Agenda Design Change Testing Code Reviews Refactoring Who am I? John Deters jadeters@comcast.net Son of a programmer Programming computers all my life I have

More information

Orbix TS Thread Library Reference

Orbix TS Thread Library Reference Orbix 6.3.9 TS Thread Library Reference Micro Focus The Lawn 22-30 Old Bath Road Newbury, Berkshire RG14 1QN UK http://www.microfocus.com Copyright Micro Focus 2017. All rights reserved. MICRO FOCUS, the

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 4 Part One: (continued) and 2016 www.cse.unsw.edu.au/ cs6771 2. Inline Constructors, Accessors and Mutators Question (from 2015): In the week 3 examples, constructors

More information

Objects Managing a Resource

Objects Managing a Resource Objects Managing a Resource 1 What is a Resource Respects Release/Acquire protocol files (open/close) memory allocation (allocate/free) locks (acquire/release). 2 What is a Resource Objects when constructed,

More information

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information