Академический Документы
Профессиональный Документы
Культура Документы
A pointer variable is one that stores an address. We can declare pointers as follows
int* p; .This means that p stores the address of a variable of type int.
x = *y;
y
1776
1775
1776
1776
Memory
25
25
X
Output
Pointer to Object
A pointer can also refer to an object of a class.
The member function of an object can be accessed through pointers by using
symbol
->
The symbol is known as member access operator.
ptr->myClass_func();
Syntax:
ptr-> member
ptr : it is the name of the pointer that reference an object.
> : it is used to access a member of object
member: it is the name of class member to be accessed.
How to
What is polymorphism
Polymorphism is a technique that allows you to set a base object equal to one
or more of its derived objects.
After the assignment, the base acts in different ways, depending on the traits
of the derived object that is currently assigned to it. The base object that acts
in many different ways, hence the name "polymorphism," which translates
literally to "many form."
However, you cannot call one of the derived methods that do not also belong
to the base. The base doesn't know about those methods, so the compiler
won't let you call them. In other words, the base may be able to call some of
the derive functions, but it is still a variable of the base type
If some of the methods in a base class are defined as virtual, each of the
descendants can redefine the implementation of these methods. The key
elements that define a typical case of polymorphism are a base class and the
descendants that inherit a base class's methods. In particular, the fanciest
type of polymorphism involves virtual methods that are inherited from a base
class
int Show(int a)
float Show(float a)
Function Declaration
Function calling
Show(5)
Show(4.0)
Show(2,3)
The calls to the overloaded methods are resolved at the compile time. This
helps in creating faster programs.
However, since all such calls must be resolved at compile time, it deprives us
from the flexibility of plugging the new code at the runtime
Dynamic Polymorphism
In case of static polymorphism, for the overloaded functions,
the compiler resolves which function to call at the compile
time
In case of dynamic polymorphism, this decision is delayed
until the runtime
C++ supports run-time binding through virtual functions.
Polymorphism is thus implemented by virtual functions and run-time binding
mechanism in C++.
Output:
Base
Base
As you can see, the function in the base class is always executed. The compiler ignores
the
contents of the pointer ptr and chooses the member function that matches the type of the
pointer,
Output:
Derv1
Derv2
ptr
Base
&Derv1
ptr -> show()
Show()
Derv1
Show()
ptr
&Derv2
Derv2
ptr
Base
&Derv1
ptr -> show()
ptr
&Derv2
Show()
Derv1
Show()