Lesson 13-C++ Object-Oriented Programming

Class Inheritance and Subtypes

Inheritance Types

  • Public inheritance (public): The public and protected members of the base class remain public and protected in the derived class, while private members are not visible.
  • Protected inheritance (protected): The public and protected members of the base class become protected members in the derived class, private members are not visible.
  • Private inheritance (private): All members of the base class become private members in the derived class.

Access Control

  • Public members (public): Can be accessed by external code of the class.
  • Protected members (protected): Can only be accessed within the class and derived classes.
  • Private members (private): Can only be accessed within the class.

Example Code

Below is a simple example showing how to use public inheritance to create a derived class Student that inherits from the base class Person.

#include <iostream>
#include <string>

// Define base class Person
class Person {
public:
    std::string name;
    int age;

    // Constructor
    Person(const std::string& n, int a) : name(n), age(a) {}

    // Public member function
    void introduce() const {
        std::cout << "Hello, my name is " << name << " and I am " << age << " years old." << std::endl;
    }

protected:
    std::string address; // Protected member

private:
    std::string phoneNumber; // Private member
};

// Define derived class Student
class Student : public Person {
public:
    int studentID;

    // Constructor
    Student(const std::string& n, int a, int id) : Person(n, a), studentID(id) {}

    // Override base class member function
    void introduce() const override {
        std::cout << "Hello, my name is " << name << " and I am " << age << " years old. My student ID is " << studentID << "." << std::endl;
    }
};

int main() {
    Student s("Alice", 20, 12345);
    s.introduce(); // Call overridden member function

    // The following code will not compile because it attempts to access private or protected members
    // s.address = "123 Main St"; // Error: address is a protected member
    // s.phoneNumber = "555-1234"; // Error: phoneNumber is a private member

    return 0;
}

Explanation

  • The Person class has public members name and age, a protected member address, and a private member phoneNumber.
  • The Student class inherits the public access rights of name and age from the Person class through public inheritance.
  • The Student class can override the introduce() method, demonstrating polymorphism.
  • Attempting to access address or phoneNumber will result in a compilation error because they are protected and private members, respectively.

Derivation

In C++, a derived class is a class that inherits from one or more base classes. A derived class can inherit members from the base class and add its own members or override base class member functions.

Member Function Overriding and Hiding

  • Overriding: When a member function in a derived class has the same name and parameter list as a virtual function in the base class, the derived class function overrides the base class function. This allows objects of the derived class to call the derived method via a base class pointer or reference.
  • Hiding: When a member function in a derived class has the same name as a member function in the base class but with a different parameter list, the derived class function does not override the base class function but hides it.

Constructors and Destructors

  • Constructors are not inherited, but the base class constructor must be explicitly called in the derived class constructor.
  • Destructors: If the base class has a virtual destructor, the derived class should also declare it as virtual.

Virtual Function Table and Virtual Function Calls

  • Virtual Function Table (vtable): C++ uses a virtual function table at runtime to implement virtual function calls. Each class containing virtual functions has a virtual function table containing pointers to all virtual functions.
  • Virtual Function Call: When a virtual function is called through a base class pointer or reference, the C++ runtime looks up the corresponding virtual function table and calls the correct function based on the actual object type.

Example Code

Below is an example showing how a derived class overrides a virtual function of the base class and how polymorphic calls are made through the virtual function table.

#include <iostream>

// Define base class Base
class Base {
public:
    virtual ~Base() {} // Virtual destructor
    virtual void print() const {
        std::cout << "Base class" << std::endl;
    }
};

// Define derived class Derived
class Derived : public Base {
public:
    void print() const override {
        std::cout << "Derived class" << std::endl;
    }
};

int main() {
    Base* basePtr = new Derived();
    basePtr->print(); // Output "Derived class"

    delete basePtr; // Properly release memory

    return 0;
}

Explanation

  • Virtual function (virtual void print() const): A virtual function print is defined in the Base class, and the Derived class overrides this function.
  • Polymorphic call: When calling the print function through the base class pointer basePtr, the corresponding overridden version is called based on the actual object type.
  • Virtual destructor: Ensures that the derived class destructor is also virtual, which is important for correctly destroying objects.

Multiple Inheritance

Basic Form of Multiple Inheritance

The basic form of multiple inheritance is as follows:

class Derived : public Base1, public Base2, ... {
    // Members of the derived class
};

Here, the Derived class inherits from multiple base classes Base1, Base2, etc.

Problems in Multiple Inheritance

  • Duplicate Base Class Problem (Diamond Problem): When two or more base classes inherit from the same class, the derived class may inherit the same base class multiple times, leading to duplication of data members and member functions.
  • Name Conflicts (Name Hiding): If multiple base classes have member functions or data members with the same name, name conflicts may occur.

Virtual Base Classes

To overcome the duplicate base class problem in multiple inheritance, C++ introduces the concept of virtual base classes. Virtual base classes ensure that the derived class inherits only one copy of the base class data members.

Multiple Inheritance Example

Below is an example using virtual base classes to solve the duplicate base class problem:

#include <iostream>

// Define virtual base class Base
class Base {
public:
    virtual ~Base() {} // Virtual destructor
    virtual void print() const {
        std::cout << "Base class" << std::endl;
    }
};

// Define derived class Derived1
class Derived1 : public virtual Base { // Use virtual inheritance
public:
    void print() const override {
        std::cout << "Derived1 class" << std::endl;
    }
};

// Define derived class Derived2
class Derived2 : public virtual Base { // Use virtual inheritance
public:
    void print() const override {
        std::cout << "Derived2 class" << std::endl;
    }
};

// Define multiple inheritance class MultipleDerived
class MultipleDerived : public Derived1, public Derived2 {
public:
    void print() const override {
        std::cout << "MultipleDerived class" << std::endl;
    }
};

int main() {
    Base* basePtr = new MultipleDerived();
    basePtr->print(); // Output "MultipleDerived class"

    delete basePtr; // Properly release memory

    return 0;
}

Explanation

  • Virtual base class (virtual Base): Both Derived1 and Derived2 virtually inherit from Base, so MultipleDerived inherits only one copy of Base type data members.
  • Virtual function (virtual void print() const): A virtual function print is defined in the Base class, which derived classes can override.
  • Polymorphic call: When calling the print function through the base class pointer basePtr, the corresponding overridden version is called based on the actual object type.

Virtual Functions and Virtual Inheritance

Virtual Functions

Virtual functions are key to supporting polymorphism in C++. They allow derived classes to override base class methods and enable runtime calls to derived class methods via base class pointers or references.

Virtual Inheritance

Virtual inheritance is used to solve the duplicate base class problem in multiple inheritance. When a class inherits from multiple base classes that share a common base class, without virtual inheritance, the derived class would inherit multiple copies of the base class data members, leading to duplication.

Example Code Below is an example using virtual functions and virtual inheritance:

#include <iostream>

// Define virtual base class Base
class Base {
public:
    virtual ~Base() {} // Virtual destructor
    virtual void print() const {
        std::cout << "Base class" << std::endl;
    }
};

// Define derived class Derived1
class Derived1 : public virtual Base { // Use virtual inheritance
public:
    void print() const override {
        std::cout << "Derived1 class" << std::endl;
    }
};

// Define derived class Derived2
class Derived2 : public virtual Base { // Use virtual inheritance
public:
    void print() const override {
        std::cout << "Derived2 class" << std::endl;
    }
};

// Define multiple inheritance class MultipleDerived
class MultipleDerived : public Derived1, public Derived2 {
public:
    void print() const override {
        std::cout << "MultipleDerived class" << std::endl;
    }
};

int main() {
    Base* basePtr = new MultipleDerived();
    basePtr->print(); // Output "MultipleDerived class"

    delete basePtr; // Properly release memory

    return 0;
}

Detailed Analysis of Virtual Functions

  • Virtual function (virtual void print() const): A virtual function print is defined in the Base class, which derived classes can override.
  • Override: Derived1 and Derived2 override the print function from the Base class.
  • Polymorphic call: When calling a virtual function through a base class pointer or reference, the C++ runtime calls the corresponding overridden version based on the actual object type.

Detailed Analysis of Virtual Inheritance

  • Virtual inheritance (virtual Base): Derived1 and Derived2 virtually inherit from Base, so MultipleDerived inherits only one copy of Base type data members.
  • Solving the duplicate base class problem: With virtual inheritance, even if both Derived1 and Derived2 inherit from Base, MultipleDerived will not inherit multiple copies of Base data members.

Polymorphism

Static Polymorphism

Static polymorphism is mainly achieved through function overloading and operator overloading. Function overloading allows defining multiple functions with the same name in one scope, as long as their parameter lists differ; operator overloading allows users to customize operator behavior.

Dynamic Polymorphism

Dynamic polymorphism is mainly achieved through virtual functions. Virtual functions allow derived classes to override base class functions, enabling runtime calls to derived class methods via base class pointers or references.

Example Code Below is an example using virtual functions to implement dynamic polymorphism:

#include <iostream>

// Define base class Shape
class Shape {
public:
    virtual ~Shape() {}
    virtual void draw() const {
        std::cout << "Drawing a shape." << std::endl;
    }
};

// Define derived class Circle
class Circle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a circle." << std::endl;
    }
};

// Define derived class Square
class Square : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a square." << std::endl;
    }
};

void drawShape(const Shape& shape) {
    shape.draw();
}

int main() {
    Circle circle;
    Square square;

    drawShape(circle); // Output "Drawing a circle."
    drawShape(square); // Output "Drawing a square."

    return 0;
}

Explanation

  • Virtual function (virtual void draw() const): A virtual function draw is defined in the Shape class, and derived classes Circle and Square override this function.
  • Polymorphic call: When passing Circle and Square objects to the drawShape function, the corresponding overridden version is called based on the actual object type.

Implementation Mechanism of Dynamic Polymorphism

  • Virtual Function Table (vtable): Each class containing virtual functions has a virtual function table containing pointers to all virtual functions.
  • Virtual Function Pointer (vptr): Each object has a virtual function pointer pointing to its class’s virtual function table.
  • Dynamic Binding: When calling a virtual function through a base class pointer or reference, the C++ runtime looks up the corresponding virtual function table and calls the correct function based on the actual object type.

Abstraction

An abstract class is a special class that cannot be instantiated, meaning no objects of it can be created. Abstract classes typically contain one or more pure virtual functions. Pure virtual functions are virtual functions declared but not defined in the base class and must be overridden in derived classes to provide concrete implementations.

Characteristics:

  • Abstract classes cannot be directly instantiated.
  • Abstract classes can have regular member functions and virtual functions.
  • Abstract classes can have data members.
  • Abstract classes can have constructors and destructors.
  • The main purpose of abstract classes is to serve as base classes for other classes.

Example:

#include <iostream>

// Define an abstract class Animal
class Animal {
public:
    // Pure virtual function, declared but not defined
    virtual void speak() = 0; // Must be implemented in derived classes

    // Virtual function with default implementation
    virtual void eat() { std::cout << "The animal is eating." << std::endl; }

    // Destructor
    virtual ~Animal() {}
};

// Dog class inherits from Animal
class Dog : public Animal {
public:
    void speak() override { std::cout << "Woof!" << std::endl; }
};

int main() {
    Dog myDog;
    myDog.speak(); // Output Woof!
    myDog.eat();   // Output The animal is eating.
    return 0;
}

Interfaces

In C++, interfaces are typically implemented through abstract classes because C++ does not support fully abstract interfaces in multiple inheritance like Java or C#. To achieve something similar to interfaces in Java or C#, abstract classes with pure virtual functions can be used.

Example:

#include <iostream>

// Define an interface IShape
class IShape {
public:
    virtual double area() const = 0; // Calculate area
    virtual double perimeter() const = 0; // Calculate perimeter
    virtual ~IShape() {}
};

// Circle class implements IShape interface
class Circle : public IShape {
private:
    double radius;
public:
    Circle(double r) : radius(r) {}

    double area() const override { return 3.14159 * radius * radius; }
    double perimeter() const override { return 2 * 3.14159 * radius; }
};

int main() {
    Circle circle(5.0);
    std::cout << "Area: " << circle.area() << std::endl;
    std::cout << "Perimeter: " << circle.perimeter() << std::endl;
    return 0;
}

Benefits of Using Abstract Classes and Interfaces:

Code Reuse: Abstract classes and interfaces can be inherited or implemented by multiple classes, avoiding duplicate code.

Polymorphism: By inheriting abstract classes or implementing interfaces, derived classes can have different behaviors, providing a foundation for polymorphism.

Modularity: Abstract classes and interfaces provide clear boundaries, making code easier to understand and maintain. They help break complex systems into smaller, more manageable parts.

Flexibility: New implementations can be added without modifying existing code, improving system flexibility and extensibility.

Hiding Implementation Details: Abstract classes and interfaces expose only necessary methods and properties, hiding internal implementation details, which helps improve system security.

Designing with Abstract Classes and Interfaces Suppose we need to design a graphics processing system that supports different types of graphic objects, such as circles, rectangles, etc. We can achieve this by defining an abstract class Shape, with each concrete graphic class inheriting from Shape.

Example Code:

#include <iostream>
#include <vector>

// Define an abstract class Shape
class Shape {
public:
    virtual void draw() const = 0; // Draw the shape
    virtual double area() const = 0; // Calculate area
    virtual ~Shape() {}
};

// Circle class inherits from Shape
class Circle : public Shape {
private:
    double radius;
public:
    Circle(double r) : radius(r) {}
    void draw() const override { std::cout << "Drawing a circle with radius " << radius << std::endl; }
    double area() const override { return 3.14159 * radius * radius; }
};

// Rectangle class inherits from Shape
class Rectangle : public Shape {
private:
    double width, height;
public:
    Rectangle(double w, double h) : width(w), height(h) {}
    void draw() const override { std::cout << "Drawing a rectangle with width " << width << " and height " << height << std::endl; }
    double area() const override { return width * height; }
};

int main() {
    std::vector<Shape*> shapes;

    Circle c(5.0);
    Rectangle r(4.0, 6.0);

    shapes.push_back(new Circle(5.0));
    shapes.push_back(new Rectangle(4.0, 6.0));

    for (auto shape : shapes) {
        shape->draw();
        std::cout << "Area: " << shape->area() << std::endl;
        delete shape; // Clean up memory
    }

    return 0;
}

Aggregation

In C++, aggregation (Aggregate) is a specific concept referring to classes or arrays with certain properties. Aggregate classes have the following characteristics:

  1. No user-defined constructors: Aggregate classes cannot have any user-defined constructors, meaning no explicitly declared constructors and no constructors with default parameters.
  2. At least one public parameterless constructor: Aggregate classes must have at least one public parameterless constructor, which can be default-generated.
  3. All members are public: All members (data members) of an aggregate class must be public.
  4. No private or protected members: Aggregate classes cannot have private or protected data members.
  5. No virtual functions: Aggregate classes cannot contain virtual functions.
  6. No base classes: Aggregate classes cannot inherit from other classes.
  7. No user-defined destructors: Aggregate classes cannot have user-defined destructors.

Aggregate classes are mainly used for simple data structures, such as structs, and are typically used for POD (Plain Old Data) types. Due to their simplicity and efficiency, aggregate classes are often used in C++ to create simple data containers.

Example of Aggregate Class

Below is a simple example of an aggregate class:

#include <iostream>

// Define an aggregate class
struct Point {
    int x;
    int y;
};

int main() {
    // Use list initialization to create an instance of the aggregate class
    Point p1 = {10, 20};
    std::cout << "Point p1: (" << p1.x << ", " << p1.y << ")" << std::endl;

    // Direct initialization
    Point p2{30, 40};
    std::cout << "Point p2: (" << p2.x << ", " << p2.y << ")" << std::endl;

    return 0;
}

In this example, Point is an aggregate class because it satisfies all the above conditions. It can be instantiated using list initialization or direct initialization.

Aggregate Initialization

C++11 introduced list initialization, which allows using braces {} to initialize aggregate classes. After C++20, direct initialization can also use braces {} to initialize aggregate classes.

Relationship Between Aggregation, Composition, and Aggregation

In object-oriented design, the terms “composition” and “aggregation” are also commonly mentioned, but the “aggregation” here is not the same concept as the aggregate class mentioned earlier. In object-oriented design:

  • Composition represents an “owns” relationship, where one class owns an instance of another class, and the lifecycle of that instance is bound to the owning class instance.
  • Aggregation represents an “association” relationship, where one class contains an instance of another class, but those instances can be shared between different objects.

RTTI

RTTI provides a way to determine the type of an object at runtime, which is particularly useful for implementing polymorphic behavior. C++ RTTI mainly comes in two forms:

typeid Operator:

  • The typeid operator can be used to obtain type information for an object or type.
  • It returns a std::type_info object containing type information.

dynamic_cast Operator:

  • dynamic_cast is used for safely converting pointers or references within an inheritance hierarchy.
  • If the conversion fails, dynamic_cast returns a null pointer or throws a std::bad_cast exception.

Example Code:

#include <iostream>
#include <typeinfo>

// Base class
class Base {
public:
    virtual void print() { std::cout << "Base class" << std::endl; }
    virtual ~Base() {}
};

// Derived class
class Derived : public Base {
public:
    void print() override { std::cout << "Derived class" << std::endl; }
};

int main() {
    Base* basePtr = new Derived();
    std::cout << "Type of basePtr: " << typeid(*basePtr).name() << std::endl;

    // Use dynamic_cast for safe conversion
    Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
    if (derivedPtr != nullptr) {
        derivedPtr->print();
    } else {
        std::cout << "Conversion failed." << std::endl;
    }

    delete basePtr;

    return 0;
}

Exceptions

Exception handling is a mechanism in C++ for handling runtime errors in programs. It allows the program to throw an exception when an error occurs and catch it in an appropriate place for handling.

Exception Handling Keywords:

throw: Used to throw an exception.

try: Used to mark a block of code that may throw an exception.

catch: Used to catch and handle exceptions.

finally: C++ does not have a direct finally keyword, but std::function or RAII (Resource Acquisition Is Initialization) techniques can be used to simulate similar functionality.

Example Code:

#include <iostream>
#include <stdexcept>

void divide(int numerator, int denominator) {
    if (denominator == 0) {
        throw std::runtime_error("Division by zero!");
    }
    std::cout << "Result: " << static_cast<double>(numerator) / denominator << std::endl;
}

int main() {
    try {
        divide(10, 0); // Will throw an exception
    } catch (const std::exception& e) {
        std::cerr << "Caught exception: " << e.what() << std::endl;
    } catch (...) {
        std::cerr << "Caught unknown exception." << std::endl;
    }

    return 0;
}

Copying and Overloading

Copying

Copying typically refers to creating a new copy of an object. In C++, copying can be achieved in various ways, with the most important being the copy constructor and assignment operator.

Copy Constructor:

  • The copy constructor is a special constructor used to create a new object as a copy of an existing object.
  • It usually takes only one parameter, a reference to an object of the same type.
  • The copy constructor is called when an object is used as an initialization expression to create another object.

Assignment Operator:

  • The assignment operator (operator=) is used to copy the state of one object to another.
  • It usually needs to return a reference to itself to support chained assignments.
  • The assignment operator should handle “self-assignment,” i.e., when both sides are the same object, to avoid unnecessary work.

Example Code: Suppose we have a simple class MyClass with an integer member data.

#include <iostream>

class MyClass {
private:
    int data;

public:
    MyClass(int d) : data(d) {}

    // Copy constructor
    MyClass(const MyClass &other) {
        std::cout << "Copy constructor called." << std::endl;
        data = other.data;
    }

    // Assignment operator
    MyClass& operator=(const MyClass &other) {
        if (this != &other) {
            std::cout << "Assignment operator called." << std::endl;
            data = other.data;
        }
        return *this;
    }

    int getData() const {
        return data;
    }
};

int main() {
    MyClass obj1(10);
    MyClass obj2(obj1);  // Call copy constructor
    MyClass obj3;
    obj3 = obj1;         // Call assignment operator

    std::cout << "obj1 data: " << obj1.getData() << std::endl;
    std::cout << "obj2 data: " << obj2.getData() << std::endl;
    std::cout << "obj3 data: " << obj3.getData() << std::endl;

    return 0;
}

Overloading

Overloading refers to defining multiple functions or operators with the same name but different parameter lists within a class. C++ supports function overloading and operator overloading.

Function Overloading:

  • Function overloading allows defining multiple functions with the same name in the same scope, as long as their parameter lists differ.
  • The compiler automatically selects the correct function version based on the types and number of arguments passed.

Operator Overloading:

  • Operator overloading allows defining new operator behavior for classes.
  • It is implemented by defining member functions or friend functions named operator<operator>.
  • Operator overloading can change the behavior of built-in operators to work with custom types.

Example Code: Suppose we have a simple class Complex representing complex numbers, and we want to overload the addition operator +.

#include <iostream>

class Complex {
private:
    double real;
    double imag;

public:
    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

    // Overload addition operator
    Complex operator+(const Complex &other) const {
        return Complex(real + other.real, imag + other.imag);
    }

    void print() const {
        std::cout << "(" << real << ", " << imag << ")" << std::endl;
    }
};

int main() {
    Complex c1(3.0, 4.0);
    Complex c2(1.0, 2.0);

    Complex c3 = c1 + c2;  // Overloaded addition operator

    c1.print();
    c2.print();
    c3.print();

    return 0;
}
Share your love