0

I have a usecase for two different structs (just storage of data) which share some common members, e.g.

struct Foo {
  int i;
  int j;
};

struct Bar {
  int i;
  float f;
};

The common data could be represented in a base struct but I'd like to disable the possibility of creating an object of the base struct.

jack
  • 1,658
  • 1
  • 7
  • 18
  • 3
    A protected ctor looks like the way to go: https://stackoverflow.com/q/1057221/1424875 – nanofarad Apr 30 '22 at 14:51
  • maybe *not* disable the possibility? what do you want to achieve from it? – apple apple Apr 30 '22 at 14:53
  • @nanofarad This seems to work. I'll edit my question. Then people can more easily vote for the better alternative. – jack Apr 30 '22 at 14:54
  • @appleapple I want to block unintended use. Just as a precaution. – jack Apr 30 '22 at 14:56
  • TBH, I'm not sure if it's reasonable to forbid it. The general philosophy is to not prevent programmer from doing X, unless X would actually break something - you don't know future requirements. `final` is used very sparingly in C++. Now, to justify separating a subset class, I'd need it to have a use for it somewhere (how would I name it otherwise?). The use could be "limiting repetition", but if the common subset is big (over 10 members) and it doesn't represent a single responsibility (that can be easily named), something is wrong in my design and I'd check that before trying to prevent use – Yksisarvinen Apr 30 '22 at 15:00
  • 1
    you shouldnt add answers to the question. Instead you can post an answer below. The question is for the question and answers go to answers. People don't vote for alternatives in the question, its not a survey. – 463035818_is_not_an_ai Apr 30 '22 at 15:14
  • @463035818_is_not_a_number I will move the proposed methods to separate answers. – jack Apr 30 '22 at 15:18

2 Answers2

1

If you make the constructor protected, then only derived classes can access it:

struct Base {
  int i;
 protected:
  Base() = default;
};
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • Does this automatically disable the creation of other implicitly declared constructors? – jack Apr 30 '22 at 15:00
  • 2
    @jack No, but you don't want that. Copy constructor and move constructor should be there (unless you want to make derived classes non-moveable and non-copyable as well). – Yksisarvinen Apr 30 '22 at 15:04
0

One can artificially introduce an abstract method in the base class, e.g.

struct Base {
  int i;
 protected:
  virtual void blockMe() const = 0;
};

struct Foo : public Base {
  int j;
 private:
  void blockMe() const final {}
};

struct Bar : public Base {
  float f;
 private:
  void blockMe() const final {}
};
jack
  • 1,658
  • 1
  • 7
  • 18