Object-oriented programming

Andrés Cabrera

Functional

 

Procedural

 

Object oriented

 

Paradigm

  • Functional: no state
  • Procedural: state
  • Object oriented: state and functionality handled through "Objects"
  • Objects group conceptually and functionally related data and actions

Object

  • A data structure (a way to organize data)
  • A collection of functions that can be applied to that data
(+ 3 4)
int a = 3;
int b = 4;
int c = a + b;

Numbers n;

n.setNumbers(3,4);

c = n.add();

Functional

Procedural

Object oriented

Class

  • A data type
  • Defines the "members" of the data structure
  • Is the "shape" of an object
  • Classes are instantiated as objects

 

Object

  • Each individual instance of a class
  • An Object takes up a space in memory in the "shape" of the class
  • A class can be instantiated multiple times into multiple objects

Class

  • The blueprint

 

Object

  • The house

Class

  • Data (called Attributes, fields or properties)
    • Any number of variables
    • Of any type
  • Actions/Behavior (functions, called methods)
    • Any number of functions
    • That have access to the attributes
  • An abstraction of reality/a bundling of functionality

Why?

  • An abstraction of reality/a bundling of functionality
    • This can simplify writing and reading code
  • Encapsulation
    • Implementation is separate from interface
    • Irrelevant data and functions can be hidden and protected
  • Reuse
    • Using classes can encourage and simplify reuse (debatible...)

Object Oriented languages

C++

  • C incremented by one
  • A super-set of C (mostly)
  • Began life as "C with classes" in 1979

A Class in C++

class Number
{
public:
    void setNumbers(int c, int d) {
        a = c;
        b = d;
    }
    int add() {
        return a + b;
    }
private:
    int a;
    int b;
}

A Class in Python

class Number:
    self.a = 0
    self.b = 0

    def setNumbers(self, c,d):
        self.a = c
        self.b = d
    
    def add(self):
        return a + b
}

Static and dynamic types

Number n;
Number m;

n.setNumbers(3.5,4);
m.setNumbers(5,6);

n.add(); // C returns 7, Python return 7.5
m.add(); // Return 11

Objects in C++

Number n;

n.setNumbers(3,4);
int c = n.add();

printf("%i", n.a); // Error a is a private member

Members of an object are accessed using '.'

whether they are methods or attributes

Objects in Python

n = Number();

n.setNumbers(3,4);
c = n.add();

print n.a // Not private!!

Everything is an object in Python!

 

Constructors and destructors

  • Classes often have constructor and or destructor functions
  • These are functions that are called automatically when an object is created or destroyed (e.g. a new variable is declared or when it goes out of scope)
  • Used to set up initial states and to clean up after use.
class Numbers
{
public:
    Numbers(int a = 0, int b = 0) {
        c = a;
        d = b;
    }
    ~Numbers() {
        // The destructor
    }
    int add() {
        return c + d;
    }
private:
    int c;
    int d;
}

int main(int argc, char *argv[])
{
    Numbers n(3,4);
    int c = n.add();
}

Exercise 1

  • Make a class that computes Fibonacci numbers
  • The constructor can take the number of numbers to calculate
  • It should have member functions ("methods") to set the number of Fibonacci numbers and to print the Fibonacci sequence
  • Use the class within the main() function to print the Fibonacci sequence with 5, 10 and 15 numbers.

Inheritance

  • A class can inherit from another class
    • In some languages multiple inheritance is allowed: inheriting from two or more classes
  • A child class inherits all the members (methods and attributes) of the parent class
  • It can then add functionality to the class (more members)
  • Or it can override functionality of the parent class (for functions only)
class Shape:
    def __init__(self, length):
        self.type = 'none'
    def area(self):
        return 0
    def getType(self):
        return self.type

class Square(Shape):
    def __init__(self, length):
        self.type = 'square'
        self.length = length

    def area(self):
        return self.length**2

class Circle(Shape):
    def __init__(self, radius):
        self.type = 'circle'
        self.radius = radius
    def area(self):
        return 3.14159 * self.radius**2


c = Circle(2)
print c.area() # prints 12.56636 (4 * pi)


c = Square(2)
print c.area() # prints 4

Public Inheritance

  • Essentially, all members keep their "privacy" in the subclass
  • Public members stay public
  • Private members stay private

Private Inheritance

  • Everything from the parent class is essentially inaccessible from the child class

There's a bit more to it:

Why inherit?

  • You can include a member of the type inside your class, after all... (called class composition)
  • To override functionality
  • To construct "is a" relationships (interface inheritance)
  • To inherit implementations (to bundle functionality)

Anatomy of a Python Class

  • Everything in Python is an object!
  • Definition:
    • class ClassName(BaseClass):
    • class ClassName:
  • Constructor:
    • def __init__(self, arg1, arg2):
  • Members:
    • Attributes:
      • self.AttributeName
    • Methods:
      • def method(self, arg1, arg2 ...):
      • self.method(arg1, arg2)
class Shape:
    def __init__(self, length):
        self.type = 'none'
    def area(self):
        return 0
    def getType(self):
        return self.type

class Square(Shape):
    def __init__(self, length):
        self.type = 'square'
        self.length = length

    def area(self):
        return self.length**2

class Circle(Shape):
    def __init__(self, radius):
        self.type = 'circle'
        self.radius = radius
    def area(self):
        return 3.14159 * self.radius**2


c = Circle(2)
print c.area() # prints 12.56636 (4 * pi)


c = Square(2)
print c.area() # prints 4

Anatomy of a C++ Class

  • Definition:
    • class ClassName {}
  • Constructor:
    • ClassName(int arg1, ...) {}
  • Members and methods:
    • Declared within the function and belonging to private, public or protected sections (private is the default for C++ classes)
    • You can give default parameters in any function
    • You can implement methods (functions) separately by prepending the class name:
      • int ClassName::function(int arg1, ...) {}
class Numbers
{
public:
    Numbers(int a = 0, int b = 0) {
        c = a;
        d = b;
    }
    ~Numbers() {
        // The destructor
    }
    int add() {
        return c + d;
    }
private:
    int c;
    int d;
}

int main(int argc, char *argv[])
{
    Numbers n(3,4);
    int c = n.add();
}

Common Class idioms

  • Getter and setter functions:
    • Can be used to validate and transform values before setting private members
  • Inheritance or composition?
  • One class per file, usually separated by declaration (in a .h or .hpp file) and implementation (in a .cpp file)

Inheritance or Composition

  • Some times one might be better than the other
  • Often it's just a matter of taste

Exercise 2

  • Write a "GoldenRatio" class that has a Fibonacci class variable as a member that offers functions to:
    • Set the number of elements in the Fibonacci sequence to compute
    • return the golden ratio

C++ Namespaces

  • Classes and functions can be grouped and organized in "namespaces"
  • This is useful to avoid name clashes
  • The namespace of a function should be prepended:
    • namespace::function()
  • Or the namespace should be brought in to the global namespace:
    • using namespace 
      

C++ templates

  • Essentially a way to allow variable types (i.e. types that can vary)
  • The type is determined when compiling the program and is not fixed (i.e. each program can choose the type used)
  • You set the type for a templated class after its name, within <  and >
  • The class will internally use the type you set.
  • Writing (well written) templated classes can be tricky
  • But you might find yourself using them often

Templates

template <typename Type>
Type max(Type a, Type b) {
    return a > b ? a : b;
}

#include <iostream>

int main()
{
    // This will call max<int> by implicit argument deduction.
    std::cout << max(3, 7) << std::endl;

    // This will call max<double> by implicit argument deduction.
    std::cout << max(3.0, 7.0) << std::endl;

    // This depends on the compiler. Some compilers handle this by defining a template
    // function like double max <double> ( double a, double b);, while in some compilers 
    // we need to explicitly cast it, like std::cout << max<double>(3,7.0);
    std::cout << max(3, 7.0) << std::endl; 
    std::cout << max<double>(3, 7.0) << std::endl;
    return 0;
}

From: https://en.wikipedia.org/wiki/Template_%28C%2B%2B%29

C++ streams

  • C++ introducess the streaming operators: >> and <<
  • Streaming is similar to setting but depending on context it can mean:
    • append
    • send
    • copy
    • etc.
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    cout << "Hello World" << endl;
    return 0;
}

C++11

  • Version of C++ standardized in 2011
  • Many significant improvements
  • Has been quickly adopted by most compilers
  • But sometimes requires additional settings to build on certain platforms

Things I haven't talked about:

(But that are important and you will find mentioned often)

  • Operator overloading
  • Iterators
  • Virtual functions
  • Protected functions

Some terminology

API

  • Application program interface
  • Essentially: the documentation for a library or module
  • The public members of a shared class

Web API

  • API for exchange of information through the web

SDK

  • Software development kit
  • A bundle of software, libraries and documentation
  • Targeted to a specific task, device, hardware etc.

C++ Standard template library (STL)

  • Like the C standard library a set of classes and functions for common usage
  • Printing, network, strings, data containers (vectors, lists, etc.), functions, etc.
#include <vector>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
    vector<int> v;
    string word1 = "Hello";
    string space = " ";
    string word2 = "World";
    string out = word1 + space + word2;
    v.push_back(word1.length());
    v.push_back(word2.length());
    return 0;
}
    

Workshop

  • Write a class called GoldenRatio that inherits from Fibonacci and calculates the golden ratio from a Fibonacci sequence
  • The class should "hide" the Fibonacci functions and only provide functions to
    • Set the number of elements in the Fibonacci sequence
    • Return the Golden Ratio
    • Calculate and return the error (in percentage) from the estimation to the actual Golden Ratio

Object Oriented Programmin

By mantaraya36

Object Oriented Programmin

  • 1,670