foxneSs foxneSs - 21 days ago 6
C++ Question

How to make an abstract class member?

Let's say I have a class named

Foo
that is not supposed to be initialized. It must be inherited to be used. This makes
Foo
an abstract class without pure virtual functions.
I simplified it for the sake of example:

class Foo : Qwe
{
protected:
Bar& bar;
int baz;
Foo(int baz_) : baz(baz_) {}
public:
virtual void function_that_uses_bar() const override
{
// code that uses bar here
}
}


Example of how
Foo
is used:

class Kappa : public Foo
{
public:
Kappa() : Foo(10)
{
bar = Asd(); // Asd is a Bar
}
}


So basically only classes derived from
Foo
know what should
bar
be set to.

The error I get:
Error C2530 'Foo::bar': references must be initialized
that refers to the
Foo
's constructor.
How do I fix this?

Answer

That's because bar is a reference and references need to be initialized immediately. Change your constructor to take a reference and initialize it in Kappa's constructor:

Foo(int baz_, Bar& bar) : baz(baz_), bar(bar) {}

Kappa:

 Kappa() : Foo(10, Asd()) {}