some_math_guy
some_math_guy

Reputation: 333

how virtual functions work and what happens to new return type when assigned?

#include<iostream>
using namespace std;

class Father
{
public:
  int a=99;
  void MakeAThing(){ cout<<"MakeAThing of father called"<<endl;}
  virtual void MakeAThing2(){ cout<<"MakeAThing2 of father called"<<endl;}
};
class Child : public Father
{
public:
  int b=11;
  void MakeAThing(){ cout<<"MakeAThing of child called"<<endl;}
  virtual void MakeAThing2(){ cout<<"MakeAThing2 of child called"<<endl;}
};

int main(){

  Father *obj;

  obj = new Child();
  obj->MakeAThing();// MakeAThing of Father is called

  //code to find out if  obj becomes a Child* after new
  Father fa  
  fa=*obj;
  cout <<fa.b<<endl; // error: 'Class Father' has no member 'b'
  //which means fa remains an object of Class Father


  Father *obj2;
  obj2 = new Child();
  obj2->MakeAThing2();// MakeAThing2 of Child is called
return 1;
}

Can someone explain what is going on in the main? My try:

obj is a pointer to an object of type Father

In obj= new Child(); new allocates memory for an object of type Child and returns a pointer to void: *void, right?, so is obj being converted to a *void type or is it remaining a *Father type ? why?

In obj->MakeAThing(); MakeAThing of Father is called, why?

In obj2->MakeAThing2(); how come the keyword virtual makes the call MakeAThing2 refer to that of Child instead of that of father?

Upvotes: 0

Views: 81

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

The static type of the both pointers is Father *.

Father *obj;
Father *obj2;

So when you will try to call a member function the compiler will search its declaration in the class Father.

As a result in this statement

obj->MakeAThing();

there is called the member function of the class Father.

In this call

obj2->MakeAThing2();

the compiler will call the overriding virtual function defined in the class Child due to calling the function using the table of pointers to virtual functions. As the dynamic type of the pointer is Child * then the compiler will find the pointer to the virtual function in the object of the type Child.

Upvotes: 1

Related Questions