Making new inheritance hierarchy with the help of C++ I think about:

Why there is no inheritance from the class objects? Abstract example (on abstract C++):

struct Foo { int v; Foo(int a) : v(a) {} };
struct Buz : public Foo(2) { ... }

So, the Buz is inherited only from instance of Foo - Foo(2).

Can such idea be useful? Is there any possible implementations or related ideas?

  • 2
    What would that even mean? – user7043 Dec 10 '12 at 20:18
  • I think he's asking if a subclass can provide constants to parent-class constructors. – Blrfl Dec 10 '12 at 20:24
  • If you have template <int N> struct Foo {}; you could do struct Buz : Foo<2> {};. The different instantiations of Foo would be unrelated to each other, but you could always give them a common base. Note that N is a compile-time constant here, so you can use it for things like array sizes and template metaprogramming. – Lars Viklund Dec 10 '12 at 20:58

C++ has what you're describing, but the initialization is done as part of the constructor:

struct Buz : public Foo {
  Buz() : Foo(2) { ... };

Is there any possible implementations or related ideas?

Many languages that use prototype inheritance do things like this.

The issue you run into is that from a logic point of view, the concept is only useful in very dynamic languages where 'inheritance' doesn't mean much and the syntax is shorthand for 'put all the fields from X into Y' or in pure languages without mutable variables. If the language allows mutability even if you inherit from Foo(2) that doesn't mean it won't be Foo(3) tomorrow or that two Foo(2) instances are even equivalent - which runs you into issues when you try to see if Buz inherits from Foo(2).


You can also achieve this using templates.

template <int n>

class Foo
  int _n;


class Der : public Foo

int main()
  Foo a;
  Der d;
  return 0;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.