Syfu_H Syfu_H - 2 months ago 8
C++ Question

can I achieve contravariance in c++

I know that C++ supports invariance but it doesn't support contravariance like java
so is there a way achieve this goal on my own?

#include <iostream>
using namespace std;


class A
{
public:
virtual void Print()const{cout << "A's Print()..." << endl;}
};

class B : public A
{
public:
void Print()const{cout << "B's Print()..." << endl;}
};

void foo(A){}
void bar(B){}


int main()
{

A a;
B b;

foo(a);
foo(b);

bar(a); // cannot convert parameter 1 from 'class A' to 'class B'
bar(b);

cout << endl;
return 0;
}


is there a way to convert from child class to bass one?

Answer

There is no "contravariance" in C++. However, you can provide a conversion to a derived class with a conversion constructor in the derived class:

class A
{};

class B : public A
{
    public:
    B() {}
    B(const A&) {} // No data to copy
    // B(A&&) {} // Not needed, no data to move
};

void bar(B) {}

int main()
{
    A a;
    bar(a);
    return 0;
}

Note: This invokes a single conversion from A to B. C++ does not do more than one implicit conversion (An exception is the operator ->).