marcuthh
marcuthh

Reputation: 596

C++ - calling a base class' overridden virtual method from inside base class' operator

I have a base class, that I'll call Base, and a derived class Derived. Base class has a method called readInData(istream), which is called from inside a defined operator>> function. Derived has it's own definition of readInData(istream), but does not yet have it's own definition for the operator (inherits the definition from Base.

My question is, if Derived, uses the operator defined in base, that calls the method defined in both classes, will it be Base::readInData(istream) or Derived::readInData(istream) that gets called?

I would like Derived::readInData(istream) to be called, so will I need to also redefine the operator to do this?

Thanks, Mark

Upvotes: 0

Views: 112

Answers (2)

Ceros
Ceros

Reputation: 490

class A
{
public:
  void print()
  {
    std::cout << saySomething() << std::endl;
  }
  virtual std::string saySomething()
  {
    return "hey!";
  }
};

class B : public A
{
public:
  virtual std::string saySomething()
  {
    return "I am B!";
  }
};


int _tmain(int argc, _TCHAR* argv[])
{
  system("pause");

  B b;
  b.print();

  system("pause");
}

Output: I am B!

Upvotes: 1

Sven Nilsson
Sven Nilsson

Reputation: 1879

Since your question states that the function is virtual, it will be Derived::readInData(istream) that is called.

Upvotes: 2

Related Questions