1

Consider following code,

class Interface
{
public:
    Interface(){}
    virtual ~Interface(){}
    virtual void method1() = 0; 
                                  
    virtual void method2() = 0;
};

class Concrete : public Interface
{
private:
    int myMember;

public:
    Concrete(){}
    ~Concrete(){}
    void method1();
    void method2();
};

void Concrete::method1()
{
    // Your implementation
}

void Concrete::method2()
{
    // Your implementation
}

int main(void)
{
    Interface *f = new Concrete();

    f->method1();
    f->method2();

    delete f;

    return 0;
}

The author used Interface *f = new Concrete(); to instantiate an abstract class in the main function and later he used delete f; but the issue with new and delete is that I don't like them. Is there are an alternative way to instantiate this class?

jeffbRTC
  • 1,941
  • 10
  • 29

2 Answers2

8

You need a pointer or reference to the object for polymorphism to work, but you can create that object in whatever way you want.

Concrete c;

c.method1(); // no polymorphism, using concrete directly
c.method2();

Interface* f = &c;

f->method1(); // polymorphism through Interface pointer
f->method2();

Interface& f2 = c;

f2.method1(); // polymorphism through reference
f2.method2();

Another way to avoid manual new and delete is to use a smart pointers.

#include <memory>

std::unique_ptr<Interface> upf = std::make_unique<Concrete>();

upf->method1();
upf->method2();
super
  • 12,335
  • 2
  • 19
  • 29
1

Do you want something like this?

Concrete c;
Interface* f = &c;
Evgeny
  • 1,072
  • 6
  • 6
  • that looks good. Can't we get rid from the pointer all together? – jeffbRTC Apr 07 '21 at 06:56
  • @jeffbRTC You can also have a reference ```Interface& f = c;``` if you don't like pointers (as for pointers, the cast to ```Interface&``` is implicit). – StefanKssmr Apr 07 '21 at 07:00
  • @StefanKssmr Way better. – jeffbRTC Apr 07 '21 at 07:01
  • Construction like this ``` virtual void method1() = 0; ``` means that YOU (the developer) disable to others to instantiate this class (and compiler helps you). You can use something like this ``` virtual void method1(); ``` without =0. And you will enable others to instantiate this class. – Evgeny Apr 07 '21 at 07:02
  • @Evgeny Yeah, I used a wrong title for what I want to do. Feel free to edit :) I still don't know what's the right title is. – jeffbRTC Apr 07 '21 at 07:11