#include<iostream>
class A {
protected:
int x;
public:
A(int n){
x = n;
}
int getX(){return x;}
static A add(A a, A b){
return A(a.getX() + b.getX());
}
void print(){
std::cout << x;
}
};
class B : public A {
public:
B(int x) : A(x){
};
};
int main(){
B a(10), b(10);
B c = A::add(a, b);
c.print();
int d;
std::cin >> d;
return 0;
}
For this snippet I get an error that
main.cpp: In function ‘int main()’: main.cpp:34:17: error: conversion from ‘A’ to non-scalar type ‘B’ requested
B c = A::add(a, b);
I understand the error that the error is because I can't pass a object of class B when the parameter is of class A.
I want to know if there is any way out of this, something like B c = A::add(a.super
(), b.super()); or something like this ?
Although I can easily get rid of this error in my actual program by removing inheritance and making a object of A inside of class B, I still want to use the inheritance in my program.
Bis anAbutAis not aBso it can't cast anAinto aBBis anA. Not allAareBBtoaddbecauseBis implicitly convertible toA(be careful regarding object slicing though), but you cannot convert the result, which is of typeA, toB.