-2

I have been trying to make an equation solver,

so here is what my structure is like

Class A {
    virtual void someMethod(double time){
        // doing something here
    }
};

Class B:public A{
    virtual void someMethod(double time)
        // doing something more here
    }
};

Class C:public B{
    virtual void someMethod(double time)
        // doing something more more here
    }
};

Class D:public C{
    virtual void someMethod(double time)
        // doing something more more more here
    }
};

Class Solver {

    void static solve(A obj, double time){
      obj.someMethod(); 

    }
};

When I call Solver::solve for Class C instance, it calls method defined for Class A instance instead of calling function defined for Class C itself.. How do I tackle that?

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Muhammad Faizan
  • 1,709
  • 1
  • 15
  • 37
  • 1
    Isn't that just [the same question you keep asking again](https://stackoverflow.com/questions/26229781/how-to-pass-derived-object-in-function-as-base-object-in-c)? – Kerrek SB Oct 08 '14 at 08:26
  • its the same project but a different issue... C++ acting weird and i rely on StackOverflow to complete this project. But my ratings are going down.. Seriously not a good day at all... – Muhammad Faizan Oct 08 '14 at 08:31

2 Answers2

1

You should use pointer, or reference, not object itself, since it slice to A type. And of course someMethod should be in public section, not in private,

static void solve(A& obj, double time){
ForEveR
  • 55,233
  • 2
  • 119
  • 133
1

The problem is your parameter - it is an object of type A that is initialized with your C-object, not your C-object "viewed" through an A-reference. Instead of taking by value, take by reference:

void static solve(A& obj, double time)
//                 ^

In C++, references have to be explicitly declared as ones, with an ampersand after the actual type. Otherwise the declared entity is an object that is initialized with the corresponding initializer, in this case the argument.

Columbo
  • 60,038
  • 8
  • 155
  • 203