Home >Backend Development >C++ >Can You Create a Vector of Abstract Classes in C ?

Can You Create a Vector of Abstract Classes in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 07:41:14421browse

Can You Create a Vector of Abstract Classes in C  ?

Vector of Abstract Classes in C : A Primer

In C , abstract classes provide a way to define interfaces without implementation, allowing derived classes to inherit and implement specific behaviors. However, unlike in C#, where interfaces can be instantiated directly, abstract classes in C cannot be.

The Problem

Consider the following C example:

class IFunnyInterface
{
public:
    virtual void IamFunny() = 0;
};

This abstract class represents an interface with a single method, IamFunny. Now, let's say we want to create a vector of objects that implement this interface, such as:

std::vector<IFunnyInterface> funnyItems;

This code will result in the following compiler error:

error C2259: 'IFunnyInterface' : cannot instantiate abstract class

This error occurs because C does not allow instantiation of abstract classes.

A Workaround

One workaround is to replace the abstract class with a concrete class that throws an exception when attempting to call an unimplemented method:

class IFunnyInterface
{
public:
    virtual void IamFunny()
    {
        throw new std::exception("not implemented");
    }
};

While this workaround allows the vector instantiation, it introduces a potential pitfall: code that attempts to access the methods of an IFunnyInterface object will need to handle the exception.

An Alternative Solution

A more elegant solution is to use a vector of pointers to abstract classes:

std::vector<IFunnyInterface*> ifVec;

This approach allows for polymorphic behavior and avoids the object slicing problem that can occur with direct value storage.

By understanding the limitations of abstract class instantiation in C , you can employ appropriate workarounds or use alternatives to achieve the desired functionality in your code.

The above is the detailed content of Can You Create a Vector of Abstract Classes in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn