Home Casting to non base class but with common ancestors
Reply: 0

Casting to non base class but with common ancestors

user2031
1#
user2031 Published in April 25, 2018, 6:05 pm

Let's say we have the following classes:

class A
{
public:
   A() {}

};

class B
{
public:
   B() {}
   virtual ~B() {}
};

template<typename T>
class BB: public B
{
public:
    BB() {}
};

class C: public A, public BB<bool>
{
public:
    C() {}
};

class D: public A, public B
{
public:
    D() {}
};

Do casting a C object to class type D is possible/allowed/safe ? This in order to access non templated stuff and use polymorphism.

I tried and got the error no matching function for call to 'D::D(C&)'.

Do adding the constructor D::D(C& c): A(c), B(c) {} will suffice to do so ?

Please note that I am currently using C++11 and I must stick to it, thus I need a compatible solution, however there may be better solutions with later standards so you may still share those for the sake of my knowledge.

Edit: after reading the comments, here are some further explaination to my problem

The definition of B and BB cannot be changed, see it like classes from an API that can't modified.

Casting directly is calling the constructor and creates an new object, that's not what I want, thus it requires Indirection as mentionned in the answers.

Given this other class:

class Cbis: public A, public BB<float>
{
public:
    Cbis() {}
};

The only purpose of the class D would be to allow to store C and Cbis references in the same container and be able to access methods from both A and B classes.

In the end, it may not be possible at all as, even with common ancestors, as D is not a base class.

Therefore, what could be the alternatives ? Besides storing in two separate containers one based on A pointers and the on B pointers.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.398013 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO