Virtual functions in C + +

Source: Internet
Author: User

 in the degree Niang there found a cow man's answer, copied over http://zhidao.baidu.com/link?url=AhjH4Os7ixE7gzWxChCLyd13yQGdb47dAbSm_p1BsyKmh4_ _qlctwornkwig5x9ksdg4tymasp1syknrf47odq

Virtual functions in C + +

While it is difficult to find a C + + book or magazine that does not discuss polymorphism, most such discussions make polymorphism and the use of C + + virtual functions seem difficult. I intend to make the reader understand the virtual function implementation technique in C + + from several aspects and combining some examples in this article. Note, write this article just want to communicate with you learning experience because I learned shallow, inevitably there are some errors and shortcomings, I hope you criticize and correct, in this deep gratitude!

First, the basic concept
First, C + + uses virtual functions to achieve polymorphism. " Regardless of the class of the object that sent the message, they send a message of the same form, and the processing of the message may vary with the object that took over the message, which is known as polymorphism. "In a hierarchical construct of a class built on a base class, you can call a procedure of the same name in an object of any derived class, and the process provided by the invoked procedure can change with the class to which it belongs." A virtual function is first a member function that can be redefined in a derived class of that class and given another processing capability.

Second, definition of virtual function and redefinition in derived class

Class Name {
Public
Virtual member function description;
}

Class Name: base class Name {
Public
Virtual member function description;
}

Third, the structure of virtual function in memory

1. Let's look at an example: #include "iostream.h"
#include "string.h"

Class A {
Public
virtual void Fun0 () {cout << "a::fun0" << Endl;}
};

int main (int argc, char* argv[])
{
A;
cout << "Size of a =" << sizeof (A) << Endl;
return 0;
}
The result is as follows: Size of A = 4

2. If you add another virtual function: virtual void fun1 () {cout << "a::fun" << Endl;}
Get the same results. If you remove the virtual modifier in front of the function, class A {
Public
void Fun0 () {cout << "a::fun0" << Endl;}
};

int main (int argc, char* argv[])
{
A;
cout << "Size of a =" << sizeof (A) << Endl;
return 0;
}
The result is as follows: Size of A = 1

3. Look at the following result: Class A {
Public
virtual void Fun0 () {cout << "a::fun0" << Endl;}
int A;
int b;
};
int main (int argc, char* argv[])
{
A;
cout << "Size of a =" << sizeof (A) << Endl;
return 0;
}
The result is as follows: Size of A = 12

In fact, the virtual function in the memory structure is this:

Figure A

Under window2000, the pointer occupies 4 bytes in memory, and the virtual function stores the function address in a virtual function table (VTABLE). Look at the example below. Class A {
Public
virtual void Fun0 () {cout << "a::fun0" << Endl;}
virtual void fun1 () {cout << "a::fun1" << Endl;}
int A;
int b;
};
int main (int argc, char* argv[])
{
A;
cout << "Size of a =" << sizeof (A) << Endl;
return 0;
}

The results are as follows:
Size of A = 4

The memory structure of the virtual function is as follows, you can also find the virtual function table (VTABLE) through the function pointer, and then access each function address to verify this structure, in the foreign site author is: Zeeshan Amjad wrote "ATL on the hood in detail"

Figure II

4. Let's take a look at the memory structure of the virtual function in the inheritance, first look at the following example class A {
Public
virtual void F () {}
};
Class B {
Public
virtual void F () {}
};
Class C {
Public
virtual void F () {}
};
Class Drive:public A, public B, public C {
};
int main () {
drive D;
cout << "Size is =" << sizeof (d) << Endl;
return 0;
}
The results are as follows: Size is = 12, I believe you can see the following structure diagram will be very clear,

Might

5. Let's take a look at the use of virtual functions to achieve polymorphism, first look at an example: class A {
Public
virtual void F () {cout << "a::f" << Endl;}
};
Class B:p ublic a{
Public
virtual void F () {cout << "b::f" << Endl;}
};
Class C:p ublic A {
Public
virtual void F () {cout << "c::f" << Endl;}
};
Class Drive:public C {
Public
virtual void F () {cout << "d::f" << Endl;}
};

int main (int argc, char* argv[])
{
A;
b b;
c C;
drive D;
A.F ();
B.f ();
C.F ();
D.F ();
return 0;
}
Results: A::f
B::f
C::f
D::f

Do not explain, I believe you can see what the truth! Note: Polymorphism is not a function overload

6. Implementing dynamic connections with virtual functions during compilation, the C + + compiler determines that the program uses that function according to the parameter or function return type passed by the program to the function, and then the compiler replaces each boot with the correct function. This compiler-based substitution is called a static connection, and they are executed before the program runs. On the other hand, when a program performs polymorphism, the substitution is performed during the program execution period, and this runtime substitution is called a dynamic connection. The following example: Class a{
Public
virtual void F () {cout << "a::f" << Endl;};
};

Class B:public a{
Public
virtual void F () {cout << "b::f" << Endl;};
};
Class C:public a{
Public
virtual void F () {cout << "c::f" << Endl;};
};
void Test (A *a) {
A->f ();
};
int main (int argc, char* argv[])
{
b *b=new B;
c *c=new C;
char choice;
do{
cout<< "type B for Class B,c for class C:" <<endl;
cin>>choice;
if (choice== "B")
Test (b);
else if (choice== ' C ')
Test (c);
}while (1);
cout<<endl<<endl;
return 0;
}

In the example above, if you remove the virtual modifier from the class a,b,c, look at the printed result, and then look at the following example to see the relationship between the two. What happens if the virtual modifier in B and C is removed, and the result is not removed.

7. Call the function of the inheriting class in the base class (if this function is a virtual function) or look at the example first: Class A {
Public
virtual void fun () {
cout << "A::fun" << Endl;
}
void Show () {
Fun ();
}
};

Class B:public A {
Public
virtual void fun () {
cout << "B::fun" << Endl;
}
};

int main () {
A;
A.show ();

return 0;
}
Print Result: A::fun

In the example in 6, test (a *a) actually has a process of implicitly converting an inherited class pointer to a base-class pointer. We can see that we can invoke the inherited class function in the base class with virtual functions. However, if it is not a virtual function, only the base class function can be called after the inheriting class pointer is converted to a base class pointer. Conversely, if a base-class pointer transforms into a pointer to an inherited class, this can only be a display conversion, and the transformed inherited class pointer can call the base class and inherit the class pointer. The following example: Class A {
Public
void Fun () {
cout << "A::fun" << Endl;
}

};
Class B:public A {
Public
void Fun () {
cout << "B::fun" << Endl;
}
void Fun0 () {
cout << "B::fun0" << Endl;
}
};
int main () {
A *a=new A;
b *b=new B;
A *pa;
B *PB;
Pb=static_cast<b *> (a); The base class pointer displays conversions to the inheriting class pointer
Pb->fun0 ();
Pb->fun ();
return 0;
}

Virtual functions in C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.