2

I have the following code:

class Carb {
public:
    virtual void calorie() = 0; // pure virtual
}

class Omelette : Carb {
public:
    void calorie() {/*do something*/}; // non-virtual
}

class Breakfast {
public:
    Breakfast(const Carb &somecarb):
    my_carb(somecarb){}

private:
    const Carb &my_carb;
}


}

I understand that Carb is a virtual class therefore cannot be an instance, but we can use a pointer from the following stackoverflow questions.

C++ : Cannot declare field to be of abstract type

C++ error: cannot declare field to be of abstract type

However, it also seems to work by declaring a const reference like my code above. My question is, is it valid to have a class field to be a constant reference to a abstract class? Why does it work this way?

Community
  • 1
  • 1
SunnyIsaLearner
  • 750
  • 2
  • 13
  • 26
  • 2
    References and pointers both provide indirection; indirection is required for runtime polymorphism. Therefore, either can be used with a pure virtual class. – cdhowie May 10 '17 at 18:39
  • Just make sure the `Carb` doesn't end its lifetime before the `Breakfast`. – aschepler May 11 '17 at 00:28

0 Answers0