C++ coaching Ahmedabad, c++ language, Coaching for IT Engineering, computer training to IT Engineering, IT Computer Courses in Ahmedabad

Types of Polymorphism in C++

Polymorphism in C++ is a powerful concept that allows objects to be treated as instances of their parent class as well as an instance of their child classes. Polymorphism is derived from the Greek words “poly” which means many and “morph” which means forms. In C++ programming, there are mainly two types of polymorphism: compile-time polymorphism and runtime polymorphism.

Compile-time polymorphism, also known as static polymorphism or early binding, is achieved using function overloading and operator overloading. Function overloading allows different functions to have the same name but different parameters. This means that the compiler can decide which function to call based on the parameters passed to it.

For example, in C++, we can have multiple functions with the same name but different parameters like:

c

int add(int a, int b);

float add(float a, float b);

Similarly, operator overloading allows us to define the behavior of operators for user-defined data types. For example, we can overload the ‘+’ operator for a custom class to perform addition based on our requirements.

Compile-time polymorphism provides performance benefits as the function calls are resolved at compile time.

On the other hand, runtime polymorphism, also known as dynamic polymorphism or late binding, is achieved using inheritance and virtual functions. Inheritance allows a class to inherit properties and behaviors from another class. By using inheritance, we can create a parent class and multiple child classes, each with its own unique behavior.

Virtual functions are functions in the base class that are overridden by the derived class. They allow the function to be resolved at runtime, based on the actual object being referred to. This means that the correct function is called based on the type of object at runtime. The use of the virtual keyword in C++ indicates that the function is virtual and will be resolved dynamically.

class Shape

{

public:

virtual void draw()

{

cout << “Drawing shape” << endl;

}

};

class Circle : public Shape {

public:

void draw() override

{

cout << “Drawing circle” << endl;

}

};

class Square : public Shape

{

public:

void draw() override

{

cout << “Drawing square” << endl;

}

};

In the above example, the draw() function is declared as virtual in the base class Shape and overridden in the derived classes Circle and Square. When we call the draw() function on objects of type Shape, the actual function called will depend on the type of object.

TCCI provides the best training in C++ programming through different learning methods/media is located in Bopal Ahmedabad and ISCON Ambli Road in Ahmedabad.

For More Information:                                    

Call us @ +91 9825618292

Visit us @ http://tccicomputercoaching.com

Leave a comment