ObjectOrientedGenericFunctional

Object-Oriented, Generic, and Functional Programming

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?

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.

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    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, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery,and Matt Godbolt.

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

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

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

    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++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *