0

i have problem with constructor i want do something like this:

A<int>* first = new B<int>
A<int> *second;

second= new B<int>(*A);

I have tried use in argument list pointer,reference and value and nothing work, and i cant tell why. This is my not working constructor :

template <class T>
B<T>::B(B<T> other) 

it works with const A<T>& thanks, One more thing if i can. I must get access in this constructor to B class private class fields. And if i have only other which is A class. Can i do this in some other may?

1 Answers1

1

Assuming B<T> inherits A<T>, as you described in a comment, you are trying to downcast when you write new B<int>( some_value_of_type_A );

You have to supply a constructor that takes type A<T>, like this:

template<class T>
B<T>::B(const A<T>& other);
Community
  • 1
  • 1
Beta Carotin
  • 1,659
  • 1
  • 10
  • 27
  • Yes, and `second= new B(*A);` doesn't mean anything because A is a type and not an object... – Christophe May 24 '15 at 14:22
  • It started working, thank you. One more thing if i can. I must get access in this constructor to B class private class fields. And if i have only other which is A class. Can i do this in some other may? – Hangoverflow May 24 '15 at 14:25
  • @Hangoverflow You don't know if the `A other` actually holds a valid `B` at runtime. To find out if it does, you can use RTTI, google it. – Beta Carotin May 24 '15 at 14:29
  • I know because i have in tests that this is B class like i write you this in first code in this question. I must get whatever it B class holding in class field : value. – Hangoverflow May 24 '15 at 14:33
  • @Hangoverflow If you want to assume that `other` is a `B`, you can cast. Either using `const B& b = static_cast(other);` or `dynamic_cast` instead of `static_cast`. You should read up on the difference between the two. – Beta Carotin May 24 '15 at 14:36
  • Almost : const B& b = dynamic_cast&>(other); Besides that everything is perfect, thank you very much. You save my life ;d – Hangoverflow May 24 '15 at 14:44