Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
What would that even mean? – delnan 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
up vote 6 down vote accepted

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

struct Buz : public Foo {
  Buz() : Foo(2) { ... };
share|improve this answer
I'm doing it constantly and never though of it! – m0nhawk Dec 10 '12 at 20:25

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).

share|improve this answer

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;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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