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 ofFoo
–Foo(2)
.
Can such idea be useful? Is there any possible implementations or related ideas?
3
C++ has what you’re describing, but the initialization is done as part of the constructor:
struct Buz : public Foo {
Buz() : Foo(2) { ... };
};
0
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
{
public:
int _n;
Foo():_n(n){}
};
class Der : public Foo
{
public:
Der(){};
};
int main()
{
Foo a;
Der d;
return 0;
};