Virtual functions in C + + (i) __jquery

Source: Internet
Author: User
Tags modifier

Virtual functions in C + + (i)


Author: aber




Although it is difficult to find a C + + book or magazine that does not discuss polymorphism, most of these discussions make it difficult to use polymorphism and C + + virtual functions. In this article, I intend to make the reader understand the virtual function implementation technology in C + + from several aspects and combine some examples. To illustrate, write this article just want to exchange learning experience with you because I have a shallow knowledge, there are some mistakes and deficiencies, I hope everyone criticized and corrected, in this deep thank you.

I. Basic CONCEPTS
First, C + + realizes polymorphism through virtual functions. " Regardless of the class in which the message is sent, they send a message with the same form, and the handling of the message may change with the object of the takeover message "The way it is called polymorphism." "In the hierarchy of a class built on a base class, you can invoke a procedure of the same name in the object of any derived class, and the process provided by the invoked procedure can change with the class to which it belongs. The virtual function is first a member function that can be redefined in the derived class of the class and given another processing function.

Definition of virtual function and redefinition in derived class

Class class Name {public
:
       virtual member function description,
} class

class name: base class Name {public
   :
          virtual member function description;
}
      
Three, the structure of virtual function in memory

1. Let's take a 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  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 result. 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  A;
	cout << "Size of A =" << sizeof (a) << Endl;
		return 0;
}      
The result is as follows: Size of A = 1

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

In fact, virtual functions are structured in memory in this way:


Figure I

Under window2000 The pointer occupies 4 bytes in memory, and the virtual function saves the address of the function 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  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 through the function pointer, first find the virtual function table (VTABLE), and then access to each function address to verify the structure, in the foreign web site author is: Zeeshan Amjad wrote "ATL on the Hood" is described 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: the Size is = 12, I believe you will see the following structure diagram is very clear,


Figure Three

5. Let's take a look at a virtual function 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 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
      
No need to explain, I believe everyone can see what the truth. Note: Polymorphism is not a function overload

6. Implementing a dynamic connection with virtual functions during compilation, the C + + compiler determines that the program uses that function, based on the arguments that the program passes to the function, or the function return type, and then the compiler replaces each startup with the correct function. This compiler-based substitution is called a static connection, and they are executed before the program is run. On the other hand, when a program executes polymorphism, the substitution occurs during the execution of the program, which 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 connection between the two. If you remove the virtual modifier in B and C, what happens, the result is the same as not being removed.

7. Call a function of an inherited 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;
    A.show ();
	
    return 0;
}      
Print Results: A::fun

In the example in 6, test (a *a) actually has a process in which an inherited class pointer implicitly converts to a base-class pointer. We can see that using virtual functions we can invoke inherited class functions in the base class. However, if it is not a virtual function, the inheriting class pointer can only call the base class function after it has been converted to a base class pointer. Conversely, if the base class pointer transforms to an inherited class pointer, it can only be displayed and transformed, and the transformed inheriting class pointer may call the base class and the inheriting 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 the transformation Pb->fun0 () to the inheriting class pointer
    .
	Pb->fun ();
	    return 0;
}  
Resources:
1. Science Press "C + + Programming"

2. Zeeshan Amjad ATL on the Hood

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.