top of page

Dysfunctional Interfaces in C++: When a Simple Pointer Can Crash Your Application

Writer: Sunil Kumar Yadav
Sunil Kumar Yadav
20 hours ago
5 min read

C++ provides powerful features such as inheritance and runtime polymorphism that allow us to write generic and reusable code.


We often use base-class pointers or references to interact with different derived-class objects through a common interface.


But does using a base-class pointer always make an interface generic?


Let's understand this with a simple example where a seemingly valid C++ interface can lead to unexpected behavior and even application crashes.


1. Understanding the Problem


Consider a simple class hierarchy with a base class Shape and two derived classes, Circle and Shape2.

#include <iostream>

class Shape
{
public:
    virtual void draw() = 0;
    virtual ~Shape() = default;
};

class Circle : public Shape
{
private:
    int radius;
    int x;
    int y;

public:
    Circle(int r, int xPos, int yPos)
        : radius{r}, x{xPos}, y{yPos}
    {}

    void draw() override
    {
        std::cout << "Inside Circle draw\n";
    }
};

class Shape2 : public Shape
{
public:
    void draw() override
    {
        std::cout << "Inside Shape2 draw\n";
    }
};

Here, Shape is an abstract base class that provides a common interface through the virtual function draw(). Both Circle and Shape2 implement their own versions of draw().


Now, let's write a function that accepts a base-class pointer and the number of elements to process.

void poor(Shape* s, int sz)
{
    for (int i = 0; i < sz; ++i)
    {
        s[i].draw();
        std::cout << i << std::endl;
    }
}

At first glance, this looks like a perfectly reasonable generic interface. We accept a base-class pointer and iterate over multiple objects.


Let's see what happens when we call this function.



2. The Unexpected Behavior


Consider the following main() function:

int main()
{
    Circle c[10];

    poor(c, 10);

    return 0;
}

We are passing an array of 10 Circle objects to a function that accepts Shape*. Since Circle inherits from Shape, the conversion from Circle* to Shape* is valid.


The first call to draw() may work as expected:

Inside Circle draw

However, accessing subsequent elements using s[i] introduces a serious problem. Why?


Let's understand what happens internally.


3. Understanding the Root Cause


Consider the memory layout of our classes. For simplicity, let's assume the base class contains a virtual function and the derived class introduces additional data members.


Shape Object
+----------------------+
| Virtual Table Pointer|
+----------------------+

Circle Object
+----------------------+
| Shape Base Subobject |
|----------------------|
| Virtual Table Pointer|
+----------------------+
| radius               |
+----------------------+
| x                    |
+----------------------+
| y                    |
+----------------------+

A Circle object is larger than its Shape base-class subobject because it contains additional data members. Now consider the following statement:

Shape* s = c;

The pointer s points to the Shape base-class subobject of the first Circle object. When we access:

s[0].draw();
s[1].draw();
s[2].draw();

C++ pointer arithmetic uses the size of the pointed-to type. In this case:

s[i]

is equivalent to:

*(s + i)

Therefore, the pointer advances by sizeof(Shape) for every increment, not by sizeof(Circle).

Let's visualize the problem.


Actual memory layout:

Circle Array

+----------------------+
| Circle[0]            |
|----------------------|
| Shape Base Part      |
| Circle Data Members  |
+----------------------+
| Circle[1]            |
|----------------------|
| Shape Base Part      |
| Circle Data Members  |
+----------------------+
| Circle[2]            |
|----------------------|
| Shape Base Part      |
| Circle Data Members  |
+----------------------+

How the function accesses memory:

Shape* s

+----------------------+
| Shape Base Part      |  <-- s[0]
+----------------------+
       ^
       | sizeof(Shape)
       |
+----------------------+
| Somewhere inside     |  <-- s[1]
| Circle[0] / next     |
+----------------------+
       ^
       | sizeof(Shape)
       |
+----------------------+
| Somewhere inside     |  <-- s[2]
| Circle Array         |
+----------------------+

The function assumes that objects are stored consecutively with a stride of sizeof(Shape).

But the actual array contains consecutive Circle objects, whose stride is sizeof(Circle).


This is the fundamental problem with our interface.


More precisely, pointer arithmetic beyond the first Shape base-class subobject is undefined behavior because those subobjects do not form an array of Shape objects.


Depending on the compiler, memory layout, and runtime environment, the application may crash or exhibit unexpected behavior.


4. But What If the Derived Class Has No Additional Data Members?


This is an interesting observation from our example. Consider:


class Shape2 : public Shape
{
public:
    void draw() override
    {
        std::cout << "Inside Shape2 draw\n";
    }
};

Unlike Circle, Shape2 does not introduce additional data members.


On many common implementations, sizeof(Shape2) may be equal to sizeof(Shape).

So, does the original poor() function work correctly with an array of Shape2?


Not necessarily! Even if both classes have the same size, an array of Shape2 objects is still not an array of Shape objects. The pointer arithmetic problem remains.


This is an important distinction: having the same object size does not make two different types interchangeable for array pointer arithmetic.

5. How Should We Design This Interface?


The actual requirement is simple. We want to process multiple objects that implement the Shape interface, irrespective of their concrete types.


Instead of passing a pointer to the first base-class subobject and assuming contiguous base objects, we should represent the collection of polymorphic objects explicitly.


One possible solution is to use smart pointers. First, let's make sure our base class has a virtual destructor:


class Shape
{
public:
    virtual void draw() = 0;
    virtual ~Shape() = default;
};

Now we can create a collection of different derived objects.

#include <iostream>
#include <memory>
#include <vector>

class Circle : public Shape
{
public:
    void draw() override
    {
        std::cout << "Inside Circle draw\n";
    }
};

class Shape2 : public Shape
{
public:
    void draw() override
    {
        std::cout << "Inside Shape2 draw\n";
    }
};

void drawAll(const std::vector<std::unique_ptr<Shape>>& shapes)
{
    for (const auto& s : shapes)
    {
        s->draw();
    }
}

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

    shapes.emplace_back(std::make_unique<Circle>());
    shapes.emplace_back(std::make_unique<Shape2>());

    drawAll(shapes);

    return 0;
}

Output:

Inside Circle draw
Inside Shape2 draw

Here, each object is independently allocated, and the vector stores smart pointers to the base class.


The actual objects remain Circle and Shape2, so runtime polymorphism works correctly. We also get automatic resource management through std::unique_ptr.



6. Key Takeaways


  • Base-class pointers and references are useful for implementing runtime polymorphism.

  • A pointer to a base-class subobject does not automatically represent an array of derived objects.

  • Pointer arithmetic depends on the pointed-to type.

  • Passing a derived-class array to a function expecting a base-class pointer and element count can introduce undefined behavior when the function indexes the pointer.

  • Equal object sizes do not make arrays of different types interchangeable.

  • Prefer an appropriate container of pointers or references when working with collections of polymorphic objects.

  • Always provide a virtual destructor when objects may be destroyed through a base-class pointer.


Remember: A good interface should not just accept a type-compatible argument; it should also correctly represent the assumptions it makes about that argument.


In C++, a small design mistake in an interface can sometimes be much harder to debug than the actual business logic!

Comments


©2019 by EmbeddedHow. Proudly created with Wix.com

bottom of page