0

I have the following code in C++:

#include <iostream>
using namespace std ;

class A{ 
public:
  void m1(){
    cout << "A" << endl;
  }
  virtual void m2(){
    cout << "A" << endl;
  }
  void m3(){
    cout << "A" << endl;
  }
};

class B: public A{ 
public:
  void m1(){
    cout << "B" << endl ;
  }
  virtual void m2(){
    cout << "B" << endl; 
  }
  virtual void m3(){
    cout << "B" << endl;
  }
};

int main(){
  A∗ p = new B() ;
  p−>m1() ; 
  p−>m2() ; 
  p−>m3() ;
}

What will each call in main() produce? I’m see that A B A, but don't know how to explain this in a detail.

6
  • 3
    A::m1 and A::m3 are not virtual, so the code calls A::m1 and A::m3. A::m2 is virtual, so the call goes to the overriding function, B::m2. Marking functions virtual in a derived class doesn't affect the virtualness in the base class. Commented Jun 20, 2023 at 14:02
  • 2
    virtual -> call the function based in the type of the object, non-virtual -> call the function based on the type of the pointer. The former is worked out at runtime, the latter at compile time. Commented Jun 20, 2023 at 14:05
  • Fixed version which compiles and demonstrates difference between virtual and regular functions: godbolt.org/z/7GxW6rEEE Commented Jun 20, 2023 at 14:07
  • First line of your code is broken. C++ grammar doesn't care about newlines vs other whitespace.... except that the preprocessor does care. Commented Jun 20, 2023 at 14:19
  • That code will produce a memory leak in the first place. (Which looks benign when it happens in main(), but is really bad for code reusability.) Commented Jun 20, 2023 at 14:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.