-1

When a class inherits another publicly, then shouldn't all virtual functions get rewritten? Consider the code --

class A {
private:
  vector<int> v;
public
  virtual int something() {
    cout << "A" << endl;
    return v.size();
  }
}

class B : public A {
private:
  priority_queue<int> v;
public
  int something() {
    cout << "B" << endl;
    return v.size();
  }
}

Now, when I call the function something() on an object b of class B by executing the statement b.something(), I get the output A. Why is this?

ssb
  • 7,422
  • 10
  • 36
  • 61
  • Post a *complete* working example, please. What you've posted looks just fine - apart from the issue that it's obviously retyped rather than cut/pasted, as it wouldn't compile (`public` sb. `public:`) – Roddy Dec 19 '13 at 21:49
  • I adapated this from your code and it prints "B". http://ideone.com/ADQKFc - this suggests you're doing something non-obvious and not included in your example. Are you copying the B anywhere? –  Dec 19 '13 at 21:49
  • 2
    I'll bet that you're [slicing](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c) the object somewhere. – jrok Dec 19 '13 at 21:50

1 Answers1

0

Corrected the errors (see http://codepad.org/ssivYhWb)

i.e.

#include <iostream.h>

class A {
private:
  vector<int> v;
public:
  virtual int something() {
    cout << "A" << endl;
    return v.size();
  }
};

class B : public A {
private:
  priority_queue<int> v;
public:
  int something() {
    cout << "B" << endl;
    return v.size();
  }
};

int main() {
  B b;
  b.something();
   return 0;
}

It returns B - as expected

Ed Heal
  • 59,252
  • 17
  • 87
  • 127