jeudi 22 août 2019

Upcast using reference in C++

I would like to use the "Strategy" design pattern, and have just one simple question.

We have two classes: Base as an abstract class and Derived as a concrete class.

#include <iostream>

using namespace std;

class Base {
public:
    virtual void func() = 0;

};

class Derived : public Base{
public:
    virtual void func() override
    {
        printf("hello \n"); 
    }
};

int main(){

    Base * base = new Derived();
    base->func();

    Derived derived2;
    Base & base2 = derived2;
    base2.func();

    return 0;
}

Using pointer,

Base * base = new Derived();

Using reference

Derived derived2; 
Base & base2 = derived2; 

  1. Is there any way to write in one line for reference?
  2. Which method are you guys use to implement the "strategy" design pattern, using pointer or reference?

Because of the reason above, I tend to use pointer... but I would like an answer from experts.

Aucun commentaire:

Enregistrer un commentaire