What are virtual functions – Write an example?
Virtual functions are used with inheritance, they are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at run time. Virtual keyword is used to make a function virtual.
Following things are necessary to write a C++ program with run time polymorphism (use of virtual functions)
1) A base class and a derived class.
2) A function with same name in base class and derived class.
3) A pointer or reference of base class type pointing or referring to an object of derived class.
1) A base class and a derived class.
2) A function with same name in base class and derived class.
3) A pointer or reference of base class type pointing or referring to an object of derived class.
Output:
In Derived
What is this pointer?
The ‘this’ pointer is passed as a hidden argument to all non static member function calls and is available as a local variable within the body of all non static functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
The ‘this’ pointer is passed as a hidden argument to all non static member function calls and is available as a local variable within the body of all non static functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
No comments:
Post a Comment