0

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?

user3022069
  • 377
  • 1
  • 4
  • 13
  • You need to [read about *object slicing*](http://stackoverflow.com/questions/274626/what-is-object-slicing). – Some programmer dude Mar 21 '16 at 09:16
  • 1
    You can't assign an instance of A to a variable of type C as C extends A. You could make B return an instance of type C, however, which could be assigned to a variable of type A and C. – Harry Mar 21 '16 at 09:18
  • 1
    `B::addSomething()` doesn't return anything in your example. Would it construct a new A or C or how is it supposed to work? – LiMuBei Mar 21 '16 at 09:24
  • 1
    If you have a class hierarchy, you have to work with **pointers** (smart pointers preferred) and **virtual functions**. – n. m. could be an AI Mar 21 '16 at 10:21

2 Answers2

2

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){}
};
Garf365
  • 3,619
  • 5
  • 29
  • 41
Xingyao
  • 36
  • 1
  • 3
1

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;
    }
};
sergej
  • 17,147
  • 6
  • 52
  • 89