Why is a base class method called if a derived class overrides the method?

consider the following program:

class Base {
public:
    virtual void foo() const {
        cout << "Base::foo()" << endl;
    }
};

class Derived : public Base {
public:
    virtual void foo() {
        cout << "Derived::foo()" << endl;
    }
};

void func(Base& obj) {
    obj.foo();
}

void main() {
    Derived d;
    func(d); // Base::foo() is printed 
}

If I remove constthe Baseclass from the method foo, then it is called Derived::foo(). I don't seem to understand this behavior.

1) What is the reason for this behavior?

2) Is this solved at compile time or runtime?

thank

+5
source share
5 answers

In a derived class, the signature of the function is as follows:

virtual void foo(); //Derived::foo

which does not mention const. Its non-constant member function, and Base::foois a const member function . These are two different functions, because it constis part of the function signature.

virtual void foo() const; //Base::foo 

, .

, :

class Derived : public Base {
public:
    virtual void foo() const {
        cout << "Derived::foo()" << endl;
    }
};

As const . , foo.


@davka :

, const ? - ?

obj Base, . Base . , . Base .

void func(Base& obj) {
    obj.foo();  //calls Base::foo
}

, :

void func(Derived & obj) {
    obj.foo();  //calls Derived:foo
}

, Base::foo Derived.


Derived::foo Base::foo, , Derived.

Base::foo .

class Derived : public Base {
public:
    using Base::foo;         //<----------------this unhides Base::foo
    virtual void foo() {
        cout << "Derived::foo()" << endl;
    }
};

Derived (const, ) , . .

Derived unhidden, ?

void f(Derived& obj) {
    obj.foo(); //Which function? Base::foo or Derived::foo?
}
void g(const Derived & obj) {
    obj.foo(); //Which function? Base::foo or Derived::foo?
}

Derived::foo, , Base::foo, const. : const, , , , .

-: http://www.ideone.com/955aY

+6

, Derived::foo .

, , const -ness.

+3

++ , : const .

, . , :

class MyClass
{
public:
  virtual Xxx * GetXxx();
  virtual Xxx const * GetXxx() const;
  // ....
}

.

, foo , . const-, , .

+1

What you do is called "overload." When overriding, as @SLaks pointed out, the signature should be the same.

0
source

constis part of the signature. void foo() constis another function of void foo(). You do not redefine at all. That's why.

0
source

All Articles