I'm trying to call the class function A<F>::f()
from within class S
, but I'm getting the following errors when I instantiate an S
object ( S<int>s
) and call it's f
member function ( s.f()
) :
source.cpp: In instantiation of '
int S<F>::f() [with F = int]
':
source.cpp:30:21: required from here
source.cpp:22:25: error: 'A<int>
' is not an accessible base of 'S<int>
'
Note that this works when I replace return A<F>::f();
inside the declaration of class S
with return C<A, F>::f();
. But I'm wondering why I can't do it the other way...
#include <iostream>
template <typename T> class A {
public:
int f();
};
template <typename T> int A<T>::f() {
return sizeof(T);
}
template <template <typename> class E, typename D> class C : E<D> {
public:
int f() {
return E<D>::f();
}
};
template <typename F> class S : C<A, F> {
public:
int f() {
return A<F>::f();
}
};
int main() {
S<int>s;
std::cout << s.f();
}
Any help is appreciated and if you require further clarification please feel free to comment.
Update
Since this questions is resolved I guess I should post the code that actually worked:
#include <iostream>
template <typename T> class A {
public:
int f();
};
template <typename T> int A<T>::f() {
return sizeof(T);
}
template <template <typename> class E, typename D> class C : public E<D> {
public:
int f() {
return E<D>::f();
}
};
class S : public C<A, int> {};
int main() {
S s;
std::cout << s.f(); // 4
}
You can resolve ambiguity by qualifying a member with its class name using the scope resolution ( :: ) operator. The statement dptr->j = 10 is ambiguous because the name j appears both in B1 and B2 .
Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
Constructor cannot be inherited but a derived class can call the constructor of the base class.
template <typename F> class S : C<A, F>
^
You don't specify a public
inheritance, so it defaults to private
, making the base classes inaccessible.
I think it is just a matter of using public
class inheritance. Try with:
template <template<class> class E, typename D> class C : public E<D> {
public:
int f() {
return E<D>::f();
}
};
template <typename F> class S : public C<A, F> {
public:
int f() {
return A<F>::f();
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With