Differentiate between a member function and a normal function. Also, name the function which is virtually called.
Q.) Differentiate between a member function and a normal function. Also, name the function which is virtually called.
Subject: Object Oriented Programming MethodologyMember Function vs. Normal Function
In C++, functions can be classified into two broad categories: member functions and normal functions. Member functions are associated with a particular class, while normal functions are not.
Member Functions
- Definition: A member function is a function that is defined within a class and can access the private and protected data members of the class.
- Syntax:
class MyClass {
public:
void myMemberFunction();
private:
int myDataMember;
};
In this example, myMemberFunction
is a member function of the MyClass
class. It can access the private data member myDataMember
.
Normal Functions
- Definition: A normal function is a function that is not defined within a class and cannot access the private and protected data members of any class.
- Syntax:
void myNormalFunction();
In this example, myNormalFunction
is a normal function. It cannot access the private and protected data members of any class.
Virtual Functions
- Definition: A virtual function is a member function that is declared with the
virtual
keyword. Virtual functions allow for polymorphism, which is the ability for objects of different classes to respond to the same method call in different ways. - Syntax:
class MyClass {
public:
virtual void myVirtualFunction();
};
In this example, myVirtualFunction
is a virtual function of the MyClass
class. When a virtual function is called, the actual function that is executed depends on the type of object that is calling the function.
Examples
The following code demonstrates the difference between member functions, normal functions, and virtual functions:
#include
class MyClass {
public:
void myMemberFunction();
virtual void myVirtualFunction();
};
void MyClass::myMemberFunction() {
std::cout << "This is a member function." << std::endl;
}
void MyClass::myVirtualFunction() {
std::cout << "This is a virtual function." << std::endl;
}
void myNormalFunction() {
std::cout << "This is a normal function." << std::endl;
}
int main() {
MyClass object;
object.myMemberFunction(); // Calls the member function
object.myVirtualFunction(); // Calls the virtual function
myNormalFunction(); // Calls the normal function
return 0;
}
Output:
This is a member function.
This is a virtual function.
This is a normal function.
In this example, the myMemberFunction
function is called using the object of the MyClass
class. The myVirtualFunction
function is also called using the object of the MyClass
class, but the actual function that is executed is the one that is defined in the derived class (which is not shown in this example). The myNormalFunction
function is called without using an object.