Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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
2  
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
add comment

3 Answers

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
add comment

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
add comment

You can also achieve this using templates.

template <int n>

 
class Foo
{
public:
  int _n;
  Foo():_n(n){}

};

class Der : public Foo
{
public:
  Der(){};
};

int main()
{
  Foo a;
  Der d;
  return 0;
};
   
share|improve this answer
add comment

Your Answer

 
discard

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.