Reputation: 397
I have the following (simplified) C++ code.
class A
{
};
class B
{
public:
A addSomething(int something)
{
this->something = something;
}
private:
int something;
};
class C : public A
{
};
void main()
{
B variableB = B();
A variableA;
variableA = variableB.addSomething(123);
C variableC;
variableC = variableB.addSomething(456);
}
I have three classes: A
, B
and C
. B
is considered as a master or main class while C
and A
represent subclasses in my context.
Class B
has a public method whose type has to be A
and adds an integer value to its private property. Class C
extends class A
.
In the main function the master class is instantiated and its instance is used to add the integer value, which works just fine.
However, doing the same with the instance derived from class A
does not work. It returns an error saying:
no operator "=" matches these operands
I am aware that it is caused by the fact that in the master class the addSomething
function has the type of class A
, but I need it to work with its child classes as well.
Is there a way to get it working without changing class B
?
Upvotes: 0
Views: 131
Reputation: 36
Your goal is to give a A
-type-value to a C
-type-value, which is not about class B
's business. What you need to do is to write a constructor function for class C
and give the value to variableC
.
So add codes for class C:
class C : public A
{
public:
C() {}
C(A a){}
};
Upvotes: 2
Reputation: 17979
The compiler does not know how to assign an instance of A
to a variable of type C
.
If you cant change class B
, you could implement the operator=
in class C
:
class C : public A
{
public:
C& operator=(const A& a)
{
// assign A to C
return *this;
}
};
Upvotes: 1