0% found this document useful (0 votes)
195 views25 pages

C++ Polymorphism and Templates Guide

This lecture overview covers polymorphism, templates, and the Standard Template Library in C++. It discusses polymorphism basics like inheritance, virtual functions, and dynamic binding. It provides examples of polymorphism using base and derived classes. Templates are introduced as a way to reuse code for different data types. The Standard Template Library contains containers like vectors and lists, iterators to traverse containers, and algorithms. Complex numbers, vectors, and iterators are demonstrated.

Uploaded by

api-3698788
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
195 views25 pages

C++ Polymorphism and Templates Guide

This lecture overview covers polymorphism, templates, and the Standard Template Library in C++. It discusses polymorphism basics like inheritance, virtual functions, and dynamic binding. It provides examples of polymorphism using base and derived classes. Templates are introduced as a way to reuse code for different data types. The Standard Template Library contains containers like vectors and lists, iterators to traverse containers, and algorithms. Complex numbers, vectors, and iterators are demonstrated.

Uploaded by

api-3698788
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SUPA Graduate C++ Course

Lecture 3

W. H. Bell
University of Glasgow

C++ Programming for Physicists Page 1
Lecture Overview
● Polymorphism
– Basics
– Interfaces
● Templates
– Basics
– The Standard Template Library (STL)
● Introduction
● Complex Numbers
● Vectors
● Iterators
● Algorithms
C++ Programming for Physicists Page 2
Polymorphism
● Dynamic member function resolution within an 
inheritance structure.
● Requires:
– Inheritance
– A virtual member function in the base class
– A method of the same name and parameter types in 
the derived class
– Pointers or references are used to access the created 
object. 

C++ Programming for Physicists Page 3
Polymorphism
● A virtual member function is selected by the type 
of the object that the pointer points to.
● Small overhead required: look up table for 
dynamic member function resolution

C++ Programming for Physicists Page 4
An Example of Polymorphism
Without With

A simplified UML version of example 1

C++ Programming for Physicists Page 5
An Example of Polymorphism
class BasicParticle {

protected:
  virtual void calculateMass();
}; Extract from ex1/with/[Link] 

class SmearedParticle: public BasicParticle {

private:
  virtual void calculateMass();
};
Extract from ex1/with/[Link] 

C++ Programming for Physicists Page 6
An Example of Polymorphism
#include "[Link]"
#include "[Link]"

using namespace std;

int main() {
  double fourvector1[4] = {3.0, 4.0, 5.0, 7.35};

  BasicParticle *basicParticle = 
      new BasicParticle(fourvector1);
  SmearedParticle *smearedParticle = 
      new SmearedParticle(fourvector1);

  cout << basicParticle­>getMass() << endl;
  cout << smearedParticle­>getMass() << endl;
Extract from ex1/with/[Link]

C++ Programming for Physicists Page 7
An Example of Polymorphism

SmearedParticle::SmearedParticle(double *fourvector)
{
  assignFourVector(fourvector);
}
Extract from ex1/with/[Link]

● In this example:
– The SmearedParticle constructor is calling a function 
in the base class.
– The function in the base class is calling calculateMass 
in the derived class SmearedParticle.

C++ Programming for Physicists Page 8
Pure Virtual Functions
  virtual void calculateMass() = 0;

● No implementation is given for pure virtual 
functions of a class.
– Implementation must be provided in a derived class.
● An abstract base class containing only pure 
virtual functions is called an interface.
– Allows code to be written that operates on interface 
member functions.

C++ Programming for Physicists Page 9
Interfaces
int main(int argc, char *argv[]) {
  ...
  IDataRecord *dataRecord;
  if(!strcmp(argv[1],"­a")) {
    dataRecord = new AsciiRecord("ascii_file.txt",10);
  }
  else if(!strcmp(argv[1],"­b")) {
    dataRecord = new BinaryRecord("binary_file.bin",10);
  }
  ...
  fillRecord(dataRecord);
  ...
}

void fillRecord(IDataRecord *record) {
  int arr[] = {1,2,3,4,5,6,7,8,9,10};
  record­>appendRow(arr);
} Extract from ex2/[Link]

C++ Programming for Physicists Page 10
Interfaces
class IDataRecord {
 public:
  virtual int appendRow(int *rowData) = 0;
};
Extract from ex2/[Link]

#include "[Link]"

class BinaryRecord : public IDataRecord {
 public:
  BinaryRecord(char *filename, int columns);
  ~BinaryRecord(void);
  virtual int appendRow(int *rowData);
...
Extract from ex2/[Link]

C++ Programming for Physicists Page 11
Virtual Destructors
● Uses polymorphism to destroy objects within an 
inheritance structure in order.
– If α inherits from β and an object of α class in 
instantiated via new, then calling delete on a pointer 
to the  object will call both α and then  destructors
● Special case of polymorphism since the name of 
the destructors is not the same for each class.
– See text books for more information

C++ Programming for Physicists Page 12
Introducing Templates
● Templates allow code re­use where the same 
functionality is needed to operate on many 
different classes or types.
– Templates provide code generation
● Can write Class and function templates
– This course only looks at class templates.

C++ Programming for Physicists Page 13
Using a Class Template
  Array<int> arrayInt(N);
  Array<double> arrayDouble(N);

  for(i=0;i<N;i++) {
    [Link](i,i);
    [Link](i,(double)i/N);
  }
Extract from ex3/[Link] 

● Syntax “class name” <type1, type2,...> object
● Once an object has been instantiated call member 
functions as normal

C++ Programming for Physicists Page 14
Class Template Declaration
template <class T> class Array {
public:
  Array(int);
  ~Array(void);
  int getSize(void);
  T getElement(int );
  void setElement(int , T);

protected:
  T *m_array;
  int m_size;
};

/* Templates instantiations needed by g++ */
template class Array<char>;
template class Array<int>;
template class Array<float>;
template class Array<double>; Extract from ex3/[Link] 

C++ Programming for Physicists Page 15
Class Template Implementation
template <class T> Array<T>::Array(int size) {
  m_array = new T[size];
  m_size = size;
}

template <class T> T Array<T>::getElement(int element) {
  if(element<m_size && element>=0) {
    return m_array[element];
  }
  else {
    return 0;
  }
}

template <class T> void Array<T>::setElement(int element, T value) {
  if(element<m_size && element>=0) {
    m_array[element]=value;
  }
} Extract from ex3/[Link] 

C++ Programming for Physicists Page 16
Standard Template Library (STL)
● Contains a number of class templates, providing:
– Data containers of many types
● Iterators to access the elements
● Types of container more suitable to some tasks than others
– General purpose and numeric algorithms
– Complex numbers

C++ Programming for Physicists Page 17
Choosing an STL Container
vector Elements Extra Space

Elements

list

● Vector allow random access iterator and [] 
notation
● List insertion at any point is a constant

C++ Programming for Physicists Page 18
STL Complex Numbers
#include <complex>

int main() {
  std::complex<float> complexFloat(3,4);
  std::complex<double> complexDouble(­1,0);

  std::cout << complexDouble << std::endl << std::endl;

  std::cout
    << complexFloat*(std::complex<float>)complexDouble 
       << std::endl;
Extract from ex4/[Link] 

● All the standard mathematical functionality
● Ability to cast
● Stream interpretation
C++ Programming for Physicists Page 19
STL Vectors
● Larger than an array.
– Require header information to keep track of elements
● Flexible size
– Container manages memory allocation
● Elements can be accessed with an index [i] or 
via an iterator.

C++ Programming for Physicists Page 20
STL Vectors
#include <vector>

int main() {
  std::vector<int> intVector;

  std::cout << "  >> vector size=" << [Link]() << std::endl;
  for(int i=0;i<NUM;i++) {
    intVector.push_back(i);
    std::cout << "  >> vector size=" << [Link]() 
              << std::endl;
  }

  do {
    std::cout << "  >> Popping element with value=" 
              << [Link]() << std::endl;
    intVector.pop_back();
  } while(![Link]());
Extract from ex5/[Link] 

C++ Programming for Physicists Page 21
STL Iterators
● Type of smart pointer
– Syntax is very similar but not identical to that of a 
pointer
– Relationship between Iterator and Container is similar 
to that of a pointer and an array
● But, no stream interpretation for memory address.
● Use to navigate around elements of container.

C++ Programming for Physicists Page 22
STL Iterators
#include <iostream>
#include <list>

using namespace std;

int main() {
  list<char> charList;
  list<char>::iterator itr;

  itr = [Link]();
  
  cout << endl;
  while (itr != [Link]()) {
    cout << *itr << " ";
    itr++;
  }
  cout << endl;
Extract from ex6/[Link] 

C++ Programming for Physicists Page 23
STL Algorithms
#include <vector>
#include <algorithm>

int main() {
  int numberList[] = {1,4,2,5,7,2,5,4,9,4,2,7,8,0};
  std::vector<int> numbers(numberList,numberList+
      sizeof(numberList)/sizeof(int));
  std::vector<int>::iterator first;
  std::vector<int>::iterator last;

  first = [Link]();
  last = [Link]();
  std::sort(first,last);
Extract from ex7/[Link] 

● Many different algorithms:
– explore reference material or header file.

C++ Programming for Physicists Page 24
Exercises
● Session 3 examples:
– Download examples and course guide from 
[Link]
– Build and test examples
● Tutorial time should be used for consultation

C++ Programming for Physicists Page 25

You might also like