Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

c++ - Virtual function calling using dereference object

I have a base class pointer pointing to a derived class object. I am calling foo() function by using two different ways in the code below. Why does Derived::foo() get called in the first case? Shouldn't (*obj).foo() call Base::foo() function as it has already been dereferenced?

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

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

    int main() {
        Base* obj = new Derived();
   // SCENARIO 1
        (*obj).foo();
// SCENARIO 2
        Base obj1 = *obj;
        obj1.foo();

        return 0;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
// SCENARIO 1
(*obj).foo();

Note that

  1. obj is a misnomer here, since it doesn't refer to an object, but to a pointer,
  2. (*ptr).foo() is just a roundabout way to do ptr->foo().

*ptr doesn't result in an object, but in a reference Base& to the object. And a virtual function call through a reference is subject to dynamic dispatch, just as such a call through a pointer.

// SCENARIO 2
Base obj1 = *ptr;
obj1.foo();

What you do here is you create a totally new object through slicing: it just has the base class parts of *ptr. What you want instead is this:

Base& ref = *ptr;
ref.foo();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...