Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <iostream>
#include <cstring>
#include <cstdlib>

using namespace std;

class Fir
{
public:
	virtual void mfunc() { cout << "First func" << endl; }
};

class Sec : public Fir
{
public:
	virtual void mfunc() { cout << "Second func" << endl; }
};

class Thi : public Sec
{
public:
	virtual void mfunc() { cout << "Third func" << endl; }
};

int main()
{
	Thi * tptr = new Thi();
	Sec * sptr = tptr;
	Fir * fptr = sptr;

	fptr->mfunc();
	sptr->mfunc();
	tptr->mfunc();
	delete tptr;
	return 0;
}


What I have tried:

When I execute the above code, "Third func" is displayed three times. I am wondering why the result of " fptr->mfunc()" is " Third func" instead of "Second func", even though it points to a Sec object.
Posted
Updated 24-Jul-18 11:21am

Virtual methods are used "as is"; or you "override" them; you have done neither; you have simply created a "replacement" virtual method in each class.

Trying to "down cast" in this situation makes no sense.
 
Share this answer
 
That's the very purpose of the virtual functions: to allow polymorphism.
Consider, for instance the following code
C++
void draw_shapes( Shape * sh[], size_t count)
{
  for ( size_t n = 0; n < count; ++n)
    sh[n]->draw_myself();
}

every item of the array (every Shape) will draw itself depending on its real nature: a Circle and a Rectangle, for instance, will produce quite different drawings.

[Update]
Quote:
There is still a little confusing part. The inheritance relationship of the current classes is "Fir <- Sec <- Thi". If the virtual function is called, is the thi class's mFunc () function last overridden so that the same result is output all three times?


Every object performs its own mfunc code, even if the pointer declaration specifies the base class. Try:
C++
int main()
{
  Fir * p[] = { new Fir(), new Sec(), new Thi()};

  for ( size_t n = 0; n < 3; ++n)
    p[n]->mfunc();

  for ( size_t n = 0; n < 3; ++n)
    delete p[n];
  
  return 0;
}
[/Update]
 
Share this answer
 
v3
Comments
서형박 25-Jul-18 2:16am    
There is still a little confusing part. The inheritance relationship of the current classes is "Fir <- Sec <- Thi". If the virtual function is called, is the thi class's mFunc () function last overridden so that the same result is output all three times?
CPallini 25-Jul-18 3:59am    
See my updated solution.
서형박 25-Jul-18 4:28am    
Thank you so much :)
CPallini 25-Jul-18 6:34am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900