Search code examples
c++c++11abstract-classunique-ptr

Why is the declaration of std::unique_ptr valid with an abstract class


for example:

// Example program
#include <iostream>
#include <string>

class abstract_class
{
public:
    abstract_class() = default;
    ~abstract_class() = default;
    virtual void read() = 0;
};

int main()
{
    std::unique_ptr<abstract_class> x;
    std::cout << "Hello, " << "!\n";
}

I thought an Abstract Class had these Restrictions
Abstract classes can't be used for:
Variables or member data
Argument types <---------
Function return types
Types of explicit conversions

In the above code we are using the abstract class as a template argument so why isnt this an error.


Solution

  • First things first, the argument types that you've mentioned in your question is for function call arguments and not for template arguments.


    why isnt this an error.

    Because you're creating a unique pointer to the abstract class object and not an object of the abstract class itself. That is, creating a pointer(whether unique or not) to a abstract class type is allowed.

    For example, just think that you can also write the following without any error:

    abstract_class *ptr; //this also works for the same reason