Brown Bag #3 Return of the C++. Topics  Common C++ “Gotchas”  Polymorphism  Best Practices  Useful Titbits.

Slides:



Advertisements
Similar presentations
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Advertisements

Object Oriented Programming with Java
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Constructors: Access Considerations DerivedClass::DerivedClass( int iR, float fVar) : BaseClass(fVar) { m_uiRating = uiR; } Alternatively DerivedClass::DerivedClass(
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
What's new in Microsoft Visual C Preview
CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
Inheritance, Polymorphism, and Virtual Functions
Inheritance and Polymorphism CS351 – Programming Paradigms.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Chapter 12: Adding Functionality to Your Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
BASE CLASSES AND INHERITANCE CHAPTER 4. Engineer Class.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
TCP1201 OOPDS Lecture 4 1. Learning Objectives  To understand upcasting & downcasting  To understand static polymorphism and dynamic polymorphism 
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
CS212: Object Oriented Analysis and Design
Overview of C++ Templates
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Overview of C++ Polymorphism
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Problems with assn 3? Discuss at your team meeting tonight.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Design issues for Object-Oriented Languages
Chapter 2 Objects and Classes
Motivation for Generic Programming in C++
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Inheritance, Polymorphism, and Virtual Functions
Inheritance & Polymorphism
Polymorphism & Virtual Functions
CS212: Object Oriented Analysis and Design
Templates.
Polymorphism Lec
Inheritance, Polymorphism, and Virtual Functions
Array-Based Implementations
Overview of C++ Polymorphism
Final Exam Review Inheritance Template Functions and Classes
C++ Polymorphism Reference and pointer implicit type casting
Presentation transcript:

Brown Bag #3 Return of the C++

Topics  Common C++ “Gotchas”  Polymorphism  Best Practices  Useful Titbits

Common C++ “Gotchas”  Circular dependencies  Slicing  Rule of Three

Circular Dependencies  Problem:  Two classes that depend on each other  Can’t use #include in both headers // file: A.h #include “B.h” class A { B _b; }; // file: B.h #include "A.h” class B { A _a; }; // file: A.h class B; class A { B& _b; }; // file: B.h class A; class B { A& _a; };  Solution:  Use forward declarations!  Use (smart) pointers / references for members  Limit includes in headers (helps compilation)

Rule of Three  If you define one of these, define all three:  Destructor  Copy constructor  Assignment operator MyClass& MyClass::operator= (const MyClass& other) { if (this != &other) { // Do stuff } return *this; }  Otherwise implicitly generated  Latter 2 copy all class members  Copies pointers not objects  Want move/swap semantics?  Call base version from derived classes  Rule of Two: RAII destructors

Slicing  Problem:  Loss of derived class functionality  Occurs when derived class copied into base class  Especially when passing by value void Foo( BaseClass baseParam );... DerivedClass myDerived; Foo( myDerived );  Solution:  Pass by reference or pointer!  Avoid concrete base classes

Polymorphism  ‘virtual’  Implicit Override  Explicit Override  ‘final’  Abstract Classes  Interfaces  Multiple Inheritance  Virtual Class Inheritance

‘virtual’  Used to declare virtual functions.  Virtual functions can have functionality overwritten in child classes. class Animal { virtual int GetNumLegs(); }; class Dog : public Animal { virtual int GetNumLegs(); }; class Octopus : public Animal { virtual int GetNumLegs(); }; int Animal::GetNumLegs() { return 0; } int Dog::GetNumLegs() { return 4; } int Octopus::GetNumLegs() { return 8; }

Implicit Override  C++ traditionally does not require use of the ‘override’ keyword. class Parent { virtual void Foo(int i); }; class Child : public Parent { virtual void Foo(float i); };  Child::Foo does not override Parent::Foo as they have different signatures.  Compiler will not raise an error over this – this is valid declaration.

Explicit Override  C++11 introduces the ‘override’ keyword to ensure virtual functions are overwritten. class Parent { virtual void Foo(int i); }; class Child : public Parent { virtual void Foo(float i) override; };  If the base class does not contain a virtual function with the same signature, the compiler will throw an error.  Useful to ensure functions are overwritten correctly.

‘final’  C++11 also introduces the ‘final’ keyword.  This ensures that a virtual function cannot be overwritten in child classes. class Parent { virtual void Foo() final; }; class Child : public Parent { virtual void Foo() override; };  Attempting to override a virtual function declared as final will cause the compiler to throw an error.

Abstract Classes  An abstract class is one which you cannot instantiate.  Contains virtual function(s) which must be overwritten in the child class.  A class is abstract if it contains at least pure virtual function. class Parent { virtual void Foo() = 0; }; class Child : public Parent { virtual void Foo(); }; Parent parentObject; // ERROR Child childObject; // OK

Interfaces  Similar to an abstract class whose functions are all pure virtual.  Defines certain functionality that a class must implement.  Implementation of functions is individual to each class. __interface IDancer { void Dance(); }; class Fireman : public IDancer { virtual void Dance(); }; class Butcher : public IDancer { virtual void Dance(); };

Interfaces (cont.)  Objects that implement an interface can be cast to their interface type.  Allows for easy communication between otherwise unrelated object types.  Easier manipulation of objects. std::vector dancers; Fireman fireman; Butcher butcher; dancers.push_back(fireman); dancers.push_back(butcher); std::for_each(dancers.begin(), dancers.end(), [](IDancer dancer) { dancer.Dance(); });

Multiple Inheritance  Consider the following example: Animal Mammal WingedAnimal Bat class Animal { virtual void Eat(); }; class Mammal : public Animal { … }; class WingedAnimal : public Animal { … }; class Bat : public Mammal, public WingedAnimal { … };

Multiple Inheritance (cont).  If we call Bat::Eat(), which function do we call?  It is an ambiguous function call.  This is because we have two Animal base classes.  Static cast to Animal is also ambiguous.

Virtual Class Inheritance  We can use the ‘virtual’ keyword when inheriting from a class: class Animal { virtual void Eat(); }; class Mammal : public virtual Animal { … }; class WingedAnimal : public virtual Animal { … }; class Bat : public Mammal, public WingedAnimal { … };

Virtual Class Inheritance (cont.)  The ‘virtual’ keyword will ensure that when a Bat object is created, the Animal instance used by Mammal and WingedAnimal will be the same.  This will remove any ambiguity from calls to Bat::Eat().  Will also allow direct casting of Bat to Animal.

Best Practices  Const WTF  Const FTW  Preprocessor FTL  Enums FTW

Const WTF 1. const Thing* a = new Thing(); 2. Thing const * b = new Thing(); 3. Thing* const c = new Thing(); 4. const Thing* const d = new Thing(); 1. Pointer to constant object-Pointer cannot change object 2. Same as Constant pointer to object-Pointer itself cannot change 4. All the const-Neither pointe or pointed can change

Const FTW  Prefer pass-by-reference-to-const to pass-by-value (item #20)  Avoids unnecessary constructors/destructor calls  Still guarantee to caller that object won’t be changed void Foo( const Thing& input ); void Foo( Thing const & input ); Thing GetData() const;  const member functions (getters) void Foo( Thing input );

Preprocessor FTL  Avoid #define literals  Not type-safe  Not scoped  Use initialized constant instead #define SuperImportant = 42; const int SuperImportant = 42;  Avoid #define pseudo-functions  Look like function calls, aren’t  Same type/scope problems  Use initialized constant instead #define MAX(a, b) ((a < b) ? b : a); inline int MAX(int a, int b) { return (a < b) ? b : a; }

Enums FTW struct MyEnum { enum Enum { MAX }; enum class MyEnum { MAX };  Nicer and safer than preprocessor definitions  Enum classes/structs (C++ 11)  Old: Wrap Enums in struct  Now type-safe in C++ 11

Useful Titbits  Type Inference  Range-Based For Loop  Singleton Design Pattern  Treat Warnings as Errors  Visual Assist X

Type Inference (decltype)  C++11 introduces ‘decltype’ which can be used to infer the type of an object based on the declared value of another.  Useful in conjunction with ‘auto’ when heavy operator overloading and casting is required. char Foo(); int i = 0; decltype(i) a; // a is an int decltype(0) b; // b is an int decltype(Foo()) c; // c is a char

Ranged-Based For Loop  An easier way to iterate through all the elements in a sequence of objects.  Supported by:  C-style arrays  Initializer lists  Types that implement begin() and end() iterators (STL Containers). int myArray[6] = {1, 2, 3, 4, 5, 6}; int arrayTotal = 0; for (int &i : myArray) { arrayTotal += i; } std::cout << “The sum of all values is “ << arrayTotal << “.\n”; // 21

Singleton Pattern  Limit to one class instance  No public constructors  Single static instance  Semi-controversial design pattern  Don’t overuse it class S { public: static S& getInstance() { static S instance; return instance; } private: S(S const&); // Don't implement void operator=(S const&); }; Stolen from: /c-singleton-design-pattern /c-singleton-design-pattern

Treat Warnings as Errors

Visual Assist X  Intellisense++  Refactoring  Improved syntax highlighting  Keyboard shortcuts  Jump between header/source  £30 for students

Further Reading  Microsoft Developers Network (MSDN)  CPlusPlus.com