1

I have a virtual class that I use as a base class when inheriting it in other class:

Class looks like this

class Interface
{
public:
    std::string name;


    virtual ~Interface() = default;

    virtual std::vector<std::vector<double>> Calc(std::vector<std::vector<double>>  tab) {
        return std::vector<std::vector<double>>();
    } };

I inherit this class in other class:

class Robot : public virtual robot::Interface
{
public:
    IRB6400R_200_280(){...}
    std::vector<std::vector<double>> Calc(std::vector<std::vector<double>>  tab){...some code...}
 };

I initialize the class like this:

Interface myRobot = Robot();

All the properties are initialized correctly. The problem is when I call methods of the myRobot .

When I type myRobot.Calc(...) the Interface method is called. But I need to call the Calc method of the Robot class.

How can I correctly do inheritance and call Calc method from the Robot class not Interface?

  • 2
    `Interface myRobot = Robot();` <- object slicing happening here – Osyotr Sep 06 '22 at 21:58
  • 2
    You need to use a pointer, smart pointer or reference instead to avoid the object slicing problem. – drescherjm Sep 06 '22 at 22:00
  • I understand that in this line all the properties are created. But how can I keep the correct function implementation? I need to use a kind of interface of a class with the same methods names and properties, that must be called when different types of robots are initialized. The problem is that each function of robot class has the same name of the functions but different code implementations. – PetrasVestartasEPFL Sep 06 '22 at 22:01
  • 1
    I created a [mcve] that used a smart pointer: [https://ideone.com/Eh3sPx](https://ideone.com/Eh3sPx) – drescherjm Sep 06 '22 at 22:14
  • Thank you very much. Does it mean that it is only possible to do this via smart pointers? – PetrasVestartasEPFL Sep 06 '22 at 22:15
  • No you can use a regular pointer if you prefer. – drescherjm Sep 06 '22 at 22:17
  • you can only call it like: ((Robot*)myRobot)->Robot::calc(...); or dymanic_castRobot::calc(...); – Exlife Sep 07 '22 at 09:44
  • @Exlife, `Interface myRobot = Robot();` can not be made to work. `myRobot` is not a `Robot` object its a `Interface` object only. The `Robot` part of the object was sliced off and thrown away. It would be undefined behavior to `((Robot*)myRobot)->Robot::calc(...);` because `myRobot` is not a `Robot` object. – drescherjm Sep 07 '22 at 14:19
  • @drescherjm yes, i misunderstand the code, he just made a object assignment. I thought the code is: Interface* pmyRobot = new Robot(); then if "Interface" is a virtual base, you can't static cast (downcast at compile time) Interface* to Robot*, because compiler have no clue to locate Robot* entry from a virtual base entry. if "Interface" is not virtual base, then static_cast can succeed. – Exlife Sep 15 '22 at 08:31

0 Answers0