Return a pointer to a nested inner class from a generic outer class

I am new to C ++, so bear with me. I have a generic class named A. A has a nested class B. B contains the getB () method, which should return a new instance of B. However, I cannot compile my code. Here's what it looks like: #include

hijras

template <class E> class A { public: class B { public: int data; }; B * getB(); }; 

a.cpp

 #include "Ah" template <class E> A<E>::B * A::getB() { return new B(); } 

When I try to compile this, I get the following error:

 error: expected constructor, destructor, or type conversion before '*' token 

Does anyone know what I'm doing wrong?

Thanks,

helixed

UPDATE:

Thanks for the quick reply to everyone. I still have little problems with this. After making the suggestions listed here, I have something like this:

hijras

 template <class E> class A { public: class B { public: int data; }; B * getB(); }; template <class E> typename A<E>::B * A<E>::getB() { return new B(); } class C { }; 

However, when I try to use this from main, I get an error message. Here is my main method:

main.cpp

 #include "Ah" int main(int argc, char *argv[]) { A<C> *a = new A<C>(); A<C>::B *b = a.getB(); } 

When I try to compile this, I get the following error:

 error: request for member 'getB' in 'a', which is of non-class type 'A<C>*' 

Thanks again for the quick answers.

helixed

+6
c ++ templates nested-class
source share
3 answers

The compiler is not smart enough to understand that "B" is a type when "A" is a pattern. Try using typename.

 template <class E> typename A<E>::B * A<E>::getB() { return new B(); } 
+7
source share

You need to use typename in your definition to hint to the compiler that type B is a type.

 template <class E> typename A<E>::B * A::getB() { return new B; } 
+2
source share

Response to update:

You donโ€™t need new everything in C ++, in fact, it would be better if you didnโ€™t, because you would then have to explicitly highlight the selected ones or use the smart delete pointers.

So here is your code modified:

 template <class E> class A { public: class B { public: int data; }; B getB(); // Object, not pointer }; template <class E> typename A<E>::B A<E>::getB() { return B(); } #include "Ah" int main(int argc, char *argv[]) { A<C> a = A<C>(); A<C>::B b = a.getB(); } 

If you want a new class A<C> , you need to use operator-> to call methods:

 A<C>::B b = a->getB(); 
0
source share

All Articles