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 quite surprising that programming in a functional style becomes more and more important in C++. That is not only true for C++. That holds also for python, which has a lot of 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 to?
  • 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

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++ was undergoing a lot of 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. A lot more interesting than the raw numbers is the fact 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 will 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 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 get 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 from 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 behaviour of their methods and therefore change the behaviour 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. By providing the concrete type you get automatically a function or a class for this type. Generic programming provides a similar abstraction to object-oriented programming. A big difference is that polymorphism of object-oriented programming will happen at runtime; that polymorphism of generic programming will happen in C++ at compile time. That 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 (line 11 and 12). In addition, I have not to specify the type parameter (line) because the compiler can derive it from the function arguments (line 11 and 12).

The automatic type deduction of function templates will not hold for class templates. In the concrete case, I have to 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, the application of the class template Array is independent of the fact, whether I use doubles or men.

Functional programming

A 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++ to 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 now 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.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

{tooltip} title page small{end-texte}title page small Go to Leanpub/cpplibrary "What every professional C++ programmer should know about the C++ standard library". {end-tooltip}   Get your e-book. Support my blog.

 

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

Mentoring

Stay Informed about my 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

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

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 1032

Yesterday 4552

Week 42146

Month 186317

All 11667471

Currently are 157 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments