Object-Oriented, Generic, and Functional Programming

Contents[Show]

C++ is not a functional programming language. C++ has its roots in procedural and object-oriented programming. So it's pretty surprising that programming in a functional style becomes increasingly important in C++. That is not only true for C++. That also holds for Python, which has many functional features, and even for Java. Now Java has lambda functions.

 

 

In the beginning, there are the questions

In the beginning, there are many questions about functional programming in C++:

  • What functional features does C++ have?
  • Why are pure functional languages like Haskell such influential?
  • Which direction is C++ headed?
  • What are the benefits of functional programming?
  • What is functional programming?
  • What are the characteristics of functional programming?

Quite a lot of questions that I can not answer in one post. Therefore, I will answer the questions in subsequent posts.

But let me start with a non-asked question. Which programming paradigm does C++ support?

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Be part of my mentoring programs:

 

 

 

 

Do you want to stay informed about my mentoring programs: Subscribe via E-Mail.

A strong simplification


40 years is a long time in software development. Therefore, it is no big surprise that C++ underwent many metamorphoses.

C began in the early 70th of the last century. 1998 the first C++ standard was published. 13 years later, the area of modern C++ began with C++11. More interesting than the raw numbers is that each of these three steps stands for a different way of solving problems. In C, you think in procedures and structures. C++ introduces object orientation and generic programming, a new kind of abstraction. With C++11, we got the functional programming style.

ObjectOrientedGenericFunctional

 

Before I only write about functional programming, I will sketch the ideas of object-oriented, generic, and functional programming.

Object-oriented programming

Object-oriented programming is based on the three concepts of encapsulation, inheritance, and polymorphism.

Encapsulation

An object encapsulates its attributes and methods and provides them via an interface to the outside world. This property that an object hides its implementation is often called data hiding.

Inheritance

A derived class gets all characteristics from its base class. You can use an instance of a derived class as an instance of its base class. We often speak about code reuse because the derived class automatically gets all characteristics of the base class.

Polymorphism

Polymorphism is the ability to present the same interface for differing underlying data types. The term is Greek and stands for many forms.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class HumanBeing{
public:
  HumanBeing(std::stringn):name(n){}
  virtual std::string getName() const{
    return name;
  }
private:
  std::string name;
};

class Man: public HumanBeing{};

class Woman: public HumanBeing{}; 

 

In the example, you only get the name of HumanBeing by using the method getName in line 4 (encapsulation). In addition, getName is declared as virtual. Therefore, derived classes can change the behavior of their methods and therefore change the behavior of their objects (polymorphism). Man and Woman are derived from HumanBeing.

Generic programming

The key idea of generic programming or programming with templates is to define families of functions or classes. You automatically get a function or class for this type by providing the concrete type. Generic programming provides a similar abstraction to object-oriented programming. A big difference is that the polymorphism of object-oriented programming will happen at runtime; that polymorphism of generic programming will happen in C++ at compile time. That is the reason why polymorphism at runtime is often called dynamic polymorphism but polymorphism at compile is often called static polymorphism.

By using the function template, I can exchange arbitrary objects.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
template <typename T> void xchg(T& x, T& y){   
  T t= x;
  x= y;
  y= t;
};
int i= 10;
int j= 20;
Man huber;
Man maier;

xchg(i,j);
xchg(huber,maier);

 

 It doesn't matter for the function template if I exchange numbers or men (lines 11 and 12). In addition, I have not specified the type parameter (line) because the compiler can derive it from the function arguments (lines 11 and 12).

The automatic type deduction of function templates will not hold for class templates. In the concrete case, I must specify the type parameter T and the non-type parameter N (line 1).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
template <typename T, int N>
class Array{
public:
  int getSize() const{
    return N;
  }
private:
  T elem[N];
};
 
Array<double,10> doubleArray;
std::cout << doubleArray.getSize() << std::endl;

Array<Man,5> manArray;
std::cout << manArray.getSize() << std::endl;

 

Accordingly, applying the class template Array is independent of whether I use doubles or men.

Functional programming

I will only say a few words about functional programming because I will and can not explain the concept of functional programming in a short remark. Only that much. I use the code snippet of the pendants in C++ for the typical functions in functional programming: map, filter, and reduce. These are the functions std::transform, std::remove_if, and std::accumulate.

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
std::vector<int> vec{1,2,3,4,5,6,7,8,9};
std::vector<std::string> str{"Programming","in","a","functional","style."};

std::transform(vec.begin(),vec.end(),vec.begin(),
              [](int i){ return i*i; }); // {1,4,9,16,25,36,49,64,81}

auto it= std::remove_if(vec.begin(),vec.end(),
                        [](int i){ return ((i < 3) or (i > 8)) }); // {3,4,5,6,7,8}
auto it2= std::remove_if(str.begin(),str.end(),
                         [](string s){ return (std::lower(s[0])); }); // "Programming"


std::accumulate(vec.begin(),vec.end(),[](int a,int b){return a*b;}); // 362880
std::accumulate(str.begin(),str.end(),
                [](std::string a,std::string b){return a + ":"+ b;});
                // "Programming:in:a:functional:style."

 

I apply in the code snippet two powerful features of functional programming. Both are mainstream in modern C++: automatic type deduction with auto and lambda functions.

What's next?

Which functional features does C++ have? Which one will C++ get with C++17 and C++20? These are the question I will answer in the next post and the subsequent ones.

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, and Rob North.

 

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

 

My special thanks to Take Up Code TakeUpCode 450 60

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

 

 

 

 

 

 

 

 

 

 

 

 

 

Comments   

0 #1 Hanna 2017-01-13 19:16
note that std::remove_if doesn't actually erase the elements and in order to achieve that one have to use the remove- erase idiom
Quote
0 #2 Rainer Grimm 2017-01-14 07:04
Quoting Hanna:
note that std::remove_if doesn't actually erase the elements and in order to achieve that one have to use the remove- erase idiom

You are totally right, I only get with remove_if the logical end of the container. Afterwards, by using the erase-remove idiom I have the physical end. I will write in a few posts about higher order functions in C++. Than I will mention this specific point.
The key point of this post is to provide a 1000 feet perspective. So, there is a lot of oversimplification in this post.
Quote
0 #3 Irish 2017-01-25 06:53
I would like to thank you for the efforts you have put in penning this
site. I really hpe to see the same high-grade blog posts fropm yoou in tthe future as well.
In fact, your creative wwriting abilities has encouraged me to get my own, personal website now ;)
Quote
0 #4 Israel 2017-02-02 18:30
Fabulous, wat a weblolg iit is! This webpage presents valuable data to us, keep
it up.
Quote
0 #5 Donnell 2017-02-22 02:30
Thanks for this post, I am a big big fan of this internet site would like to go
along updated.
Quote
0 #6 Jordan 2017-03-09 03:49
Thanks for sharing your thoughts. I truly appreciate
your efforts and I wijll be waiting for your next post thank you once again.
Quote
0 #7 Lino 2017-04-10 01:35
This is very attention-grabbing, You're an excessively skilled
blogger. I have joined your feed and look ahead to
in the hunt for more of your fantastic post. Additionally, I've shared your site in my social networks
Quote
0 #8 Temeka 2017-06-23 10:25
Wow that was unusual. I just wrote an very long
comment but after I clicked submit my comment didn't show up.
Grrrr... well I'm not writing all that over again. Anyways, just wanted to say wonderful blog!
Quote
0 #9 Adele 2017-08-29 14:21
After looking at a numer of tthe blog posts on your web site, I
really appreciate your technique of writing a blog. I savfed it to my
bookmark website list and will be checking back in the near future.

Plewse check out my web site as well andd let me know
your opinion.
Quote
0 #10 บาคาร่า 2018-02-24 13:58
Hey very nice blog!
Quote

Stay Informed about my Mentoring

 

Mentoring

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Course: The All-in-One Guide to C++20

Course: Master Software Design Patterns and Architecture in C++

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 4307

Yesterday 6193

Week 10500

Month 32174

All 12110383

Currently are 176 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments