3

I have the following situation, I declared a const member of a superclass and now I want to initialize it within the the constructor of one of its subclasses using a list initializer.

struct Shape {
public:
    const Rect boundingRect; // the rect in which the shape is contained
};

struct Stain : Shape
{
public:
    Stain(Rect boundingRect_) : boundingRect(boundingRect_) {}
};

I am not sure if this is even possible, if I take the straightforward approach shown above, the compiler complains with the following message:

member initializer 'boundingRect' does not name a non-static data member or base class

This answer explains why it's not possible to initialize member variables of a superclass in list initiliazers of a subclass's constructor. I am wondering what the best practice might be for that situation?

Community
  • 1
  • 1
nburk
  • 22,409
  • 18
  • 87
  • 132

2 Answers2

4

You'll have to add a constructor for struct Shape and call it from your sub-class. Like so:

struct Shape {
public:
    const Rect boundingRect; // the rect in which the shape is contained

    Shape( Rect rect ) : boundingRecT( rect ) {}
};

struct Stain : Shape
{
public:
    Stain(Rect boundingRect_) : Shape (boundingRect_) {}
};
nils
  • 2,424
  • 1
  • 17
  • 31
2

You can only initialize a class's member variables and base classes here (not the base class's members).

The solution is to give Shape a constructor which accepts the initializer, e.g.:

Shape(Rect rect): boundingRect(rect) {}

and Stain invokes it like this:

Stain(Rect boundingRect_): Shape(boundingRect_) {}

If you don't want the general public using this constructor you can make it protected:.

M.M
  • 138,810
  • 21
  • 208
  • 365